Python中的Tkinter.. 井字棋游戏.. 按钮出错!
我刚开始学习tkinter,所以还是个新手。我需要帮助,因为我在尝试编写井字棋游戏。我想用一个心形按钮作为游戏的开始区域,当玩家点击这个按钮时,按钮上的图片应该变成X或者O(另一张gif图片)。所以我需要一个函数来帮助我切换按钮上的图片,但当我尝试这样做时,出现了这个错误:AttributeError: 'Button' object has no attribute 'image'。这是导致我出问题的代码部分……
class Application(object):
def __init__(self,fnt2):
self.photo = PhotoImage(file="game.gif")
self.lab1 = Label(fnt2, text="WELCOME to the GAME")
self.lab1.image = self.photo
self.lab1['background']="#BD5151"
self.lab1['foreground']="#651268"
self.lab1.image = self.photo
self.lab1.pack()
self.lab2= Label(image=self.photo)
self.lab2.image= self.photo
self.lab2['background']="#BD5151"
self.lab2.pack()
self.imm0 = PhotoImage(file="start.gif")
self.imm1 = PhotoImage(file="bianco.gif")
self.imm2 = PhotoImage(file="ics.gif")
self.Ent = Button(fnt2, text="Click To Enter The GAME")
self.Ent['relief']="groove"
self.Ent['command']=self.Ent_Click
self.Ent.pack()
def Changepic_1(self):
imm0 = PhotoImage(file="start.gif")
imm1 = PhotoImage(file="bianco.gif")
imm2 = PhotoImage(file="ics.gif")
if self.Play.image == self.imm0:
print('ciao')
def Ent_Click(self):
fnt2 = Tk()
fnt2.title("play it!")
fnt2.resizable(False,False)
for r in range(3):
for c in range(3):
self.Play = Button(image = self.imm0, command=self.Changepic_1)
self.Play.grid(row=r,column=c)
fnt2.mainloop()
1 个回答
2
试着用下面的代码来更改它:
button.config(image=...)
要找出它已经有什么图片,你需要进行比较:
button.cget("image") == image.name
(或者单独记录它的状态)
Tk不是面向对象的,所以虽然Tkinter尽量让界面看起来更像Python的风格,但使用起来可能会有点别扭。