【发布时间】:2016-06-19 14:17:57
【问题描述】:
我正在尝试实现一个简单的井字游戏程序,但在实现游戏时遇到了困难。这是我到目前为止的代码:
from Tkinter import *
click = False
class Buttons(object):
def __init__(self,master):
frame = Frame(master)
frame.pack()
self.button1= Button(frame,text=" ",height=4,width=8,
command=self.moveYes)
self.button1.grid(row=0,column=0)
self.button2= Button(frame,text=" ",height=4,width=8,
command=self.moveYes)
self.button2.grid(row=0,column=1)
self.button3= Button(frame,text=" ",height=4,width=8,
command=self.moveYes)
self.button3.grid(row=0,column=2)
self.button4= Button(frame,text=" ",height=4,width=8,
command=self.moveYes)
self.button4.grid(row=1,column=0)
self.button5= Button(frame,text=" ",height=4,width=8,
command=self.moveYes)
self.button5.grid(row=1,column=1)
self.button6= Button(frame,text=" ",height=4,width=8,
command=self.moveYes)
self.button6.grid(row=1,column=2)
self.button7= Button(frame,text=" ",height=4,width=8,
command=self.moveYes)
self.button7.grid(row=2,column=0)
self.button8= Button(frame,text=" ",height=4,width=8,
command=self.moveYes)
self.button8.grid(row=2,column=1)
self.button9= Button(frame,text=" ",height=4,width=8,
command=self.moveYes)
self.button9.grid(row=2,column=2)
def moveYes(self):
global click
global buttons
if buttons["text"] == " " and click == False:
buttons["text"]="X"
click= True
elif buttons["text"] == " " and click == True:
buttons["text"]="O"
root = Tk()
b=Buttons(root)
root.mainloop()
当我运行它时,它会说:
global name 'buttons' is not defined
我猜我的第二种方法不正确。我不明白如何访问按钮和比较值以便更改文本。
我现在应该从双人模式开始,然后再转向人工智能吗?
【问题讨论】:
-
如何声明一个全局变量
buttons,就像使用click一样? -
@schwobaseggl 我试过了,但这也无济于事。 :( 可能是我使用单个变量访问单个按钮的方式是错误的吗?
-
@momo 名称
buttons未在moveYes函数之外定义。这就是您看到该错误的原因。通常,global用于使变量在函数内部 可访问,尽管它最初是在该函数外部 定义的。顺便提一句。您可以通过在两个for循环中定义按钮来减少代码重复。
标签: python python-2.7 tkinter tic-tac-toe