【发布时间】:2019-05-08 23:08:23
【问题描述】:
如果它不是目标按钮,我想添加一个在按下按钮时破坏按钮(以及所有更高/更低的按钮)的功能。
我希望这能澄清一点。
import tkinter as tk
from tkinter import ttk
import random
window = tk.Tk()
window.title('The Game')
window.geometry('1000x850')
target = random.randint(1,10)
words = []
for j in range(1, 11):
unit = "box" + str(j)
words.append(unit)
a=0
lives = 3
for i in words:
a = a + 1
def btn_press(event):
guess = event.widget['text']
global lives
lives -= 1
lives_rem.config(text = 'Lives remaining: ' + str(lives))
if guess == target:
print('you win')
window.destroy()
elif lives == 0:
print('you lose')
window.destroy()
elif guess > target:
#in this case, the button pressed and all of the higher ones should be destroyed
print('too high')
elif guess < target:
#in this case, the button pressed and all of the lower ones should be destroyed
print('too low')
i = tk.Button(window, text = a)
i.config(height = '3', width = '6')
i.bind('<Button-1>', btn_press)
i.place(x = -50 + a * 70, y = 25)
lives_rem = tk.Label(window, text = "Lives remaining: " + str(lives), fg = 'red')
lives_rem.place(x = 800, y = 50)
window.mainloop()
【问题讨论】:
-
最好将其编辑为MCVE,以便我们可以复制/粘贴它并自己运行它。否则,我们的答案可能会有错误/错别字,您需要对其进行整理。
-
你可以使用这个extra arguments trick来传递`btn_press()`回调函数额外的参数(例如被按下的
Button——你代码中的变量i)。 -
如果
i是for循环中使用的变量,你不应该重新分配它来保存按钮的引用。 -
@acw1668 是的,我在实际代码中使用了另一个变量。
-
@martineau 谢谢,真的很有帮助!找到按钮的名称后,删除或销毁按钮的正确方法是什么?
标签: python for-loop button tkinter command