【发布时间】:2019-11-21 00:21:15
【问题描述】:
我设置了一个 tkinter 按钮,用于将字符串发送到一个空列表,以便在计算机随机选择的另一个字符串之间进行比较。一切都相应地工作,除了在我能够单击 tkinter 按钮之前执行以下关于如何处理以前的空列表的代码。我知道这是编写石头剪刀布游戏的一种奇怪方式。发生的情况是当单击“rock”按钮时,字符串“rock”被发送到一个空列表进行存储。然后计算机从石头、纸和剪刀三个弦中选择一个。该字符串被放入另一个空列表中进行存储,然后立即与 tkinter 按钮中存储的第一个字符串进行比较。这将使我能够确定谁获胜或是否平局。
# Buttons for user to choose (Rock,Paper,Scissors).
button = Button(root, text="Rock", command=lambda: button_press.append("Rock"))
button.pack()
button_2 = Button(root, text="Paper", command=lambda: print("Paper"))
button_2.pack()
button_3 = Button(root, text="Scissors", command=lambda: print("Scissors"))
button_3.pack()
# Empty list for button value to be placed and compared with computers random.choice
button_press = []
comp_press = []
# Computer picks between the three options (Rock, Paper, Scissors)
rps = ["Rock"]
comp_pick = random.choice(rps)
comp_press.append(comp_pick)
if button_press == comp_press:
print("Draw!")
else:
print("Nothing")
【问题讨论】:
-
请将您的代码以文本形式发布。作为屏幕截图的代码绝不是一个好主意!
-
始终将代码、数据和完整的错误消息作为有问题的文本。
-
您的问题是您没有将功能分配给按钮。您为按钮分配了一些无用的 lambda,并在定义按钮后尝试运行一些代码。您为此拥有
command=- 分配功能,在您单击按钮后运行您的代码。command=some_function_which_runs_code_after_pressing_button -
建议您阅读对Tkinter — executing functions over time 的已接受答案,因为这听起来与您想要做的相似。
标签: python python-3.x tkinter