PythonTkinter 实现一个简单游戏

这两天学习了一些python基础知识,也学习了Python GUI编程 - Tkinter, 想起以前上java课的实验有个题目是这样的,刚才用Python实现了一下

PythonTkinter 实现一个简单游戏_第1张图片

代码如下:

from tkinter import *
from random import *

def callback(event):
    global r
    if(event.widget == blist[r]):
        a = r    #暂存上次随机数
        vlist[r].set("NULL")
        while( r == a):
            r = randint(0,8)
        vlist[r].set("Hiya")

root = Tk()

vlist = []
blist = []

for i in range(9):
    var = StringVar()
    var.set("NULL")
    vlist.append(var)

j = -1
for i in range(9):
    if ( i % 3 == 0):
        j = j+1
    b = Button(root, height = 3, width = 10, textvariable = vlist[i])
    b.bind("", callback)
    b.grid(row = j, column = i % 3)
    blist.append(b)

r = randint(0,8)
vlist[r].set("Hiya")

mainloop()

你可能感兴趣的:(Python)