【问题标题】:How to pause code execution until I click tkinter button?如何在单击 tkinter 按钮之前暂停代码执行?
【发布时间】: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


【解决方案1】:

GUI 中的Button 不会等到您按下它。它只定义了 mainloop() 应该显示什么窗口小部件。 Button 之后的所有代码都会立即执行 - 甚至在您看到窗口之前。

您的问题是您为按钮分配了无用的 lambda,但您应该分配检查计算机选择与用户选择的功能。

import tkinter as tk
import random

# --- functions ---

def check(user):
    computer = random.choice(rps)
    print(user, computer)

    if user == computer:
        print("Draw!")
    else:
        print("Nothing")

# --- main ---

rps = ["Rock", "Paper", "Scissors"]

root = tk.Tk()

button = tk.Button(root, text="Rock", command=lambda:check("Rock"))
button.pack()

button_2 = tk.Button(root, text="Paper", command=lambda:check("Paper"))
button_2.pack()

button_3 = tk.Button(root, text="Scissors", command=lambda:check("Scissors"))
button_3.pack()

root.mainloop() # start program

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多