我想检查一下,如果附加到列表中的按钮有文本,并且如果所有文本都包含文本,则可以重新启动游戏。我无法检查,如果按钮有文本,并且,因为它们是由for循环创建的,所以我无法逐个检查。有没有办法像这样检查,还是我会尝试其他的东西?我很抱歉,如果答案很明显,我在其他地方找不到,我是初学者。
以下是代码:
import tkinter as tk
from functools import partial
class ButtonTest():
def __init__(self, master):
self.parent = master
self.buttons_list = []
for i in range(5):
for j in range(3):
button_num = i * 3 + j
button = tk.Button(self.parent, height=6, width=12)
button.grid(row=i, column=j)
button.bind("<Button-1>", partial(self.click, button_num))
self.buttons_list.append(button)
self.counter = []
#def check_winner():
def click(self, button_num, event):
this_button = self.buttons_list[button_num]
the_actual_counter = len(self.counter)
if the_actual_counter % 2 == 0:
this_button["text"] = "X"
else:
this_button["text"] = "O"
self.counter.append("element")
master = tk.Tk()
BT = ButtonTest(master)
master.mainloop()
答案 0 :(得分:0)
如果L = [b1,b2,b3](你通过追加创建)那么,
def check_winner:
c=0
for i in L:
if i.cget("text")=="":
print("GAME OVER") # or whatever you want
c=1
break
if c==0:
print("PLAY AGAIN")
答案 1 :(得分:0)
使用buttons=[bttn1, bttn2, etc.]
(或您称之为的任何内容),然后您可以使用all
执行此操作:
def check_winner:
again=all(i.cget("text") for i in buttons)
if again:
print("play again?") # or whatever
else:
print("game over!") # or whatever