在 Python Tkinter 中,button.configure() 命令未在 while 循环内运行

Mad*_*wal 0 python tkinter button while-loop

我正在尝试根据 while 循环确定的值来配置按钮,turn该值由 while 循环确定game_over

while 循环干扰了 tkinter 的主循环。我似乎无法找到解决这个问题的方法。

这是代码。

from tkinter import *
connect = Toplevel()

col1 = Button(connect, width=10, height=4, text=" ")
col1.grid(row=0, column=1)

game_over = False
turn = 0

while not game_over:
    if turn == 0:
        col1.configure(bg="#FE6869")
        x=input("Enter something")
        if x=="yes":
            game_over=True
        else:
            continue   
    else:       
        col1.configure(bg="#FFFC82")
        x=input("Enter something")
        if x=="no":
            game_over=True
        else:
            continue
    turn += 1
    turn = turn % 2

connect.mainloop()
Run Code Online (Sandbox Code Playgroud)

ste*_*ATO 5

首先,我不建议使用潜在的无限 while 循环。其次,您应该检查如何创建 tkinter 应用程序,在创建任何顶级小部件之前首先创建根窗口。接下来,按钮可以执行指定为命令的功能。最后,如果您使用基于 GUI 的方法,您也可以从 GUI 获取用户输入。我根据您的代码制作了一个示例应用程序。我强烈建议您在继续之前观看一些有关 tkinter 的教程。

import tkinter as tk
import tkinter.simpledialog as sd


def start():
    global turn
    global game_over

    if not game_over:
        if turn == 0:
            col1.configure(bg="#FE6869")
            x=sd.askstring('User Input', 'Enter something')
            if x=="yes":
                game_over=True
                end = tk.Label(connect, text='GAME OVER')
                end.grid(row=1, column=0)
            else:
                pass
        else:
            col1.configure(bg="#FFFC82")
            x=sd.askstring('User Input', "Enter something")
            if x=="no":
                game_over=True
                end = tk.Label(connect, text='GAME OVER')
                end.grid(row=1, column=0)
            else:
                pass
        turn += 1
        turn = turn % 2


connect = tk.Tk()

turn = 0
game_over = False

col1 = tk.Button(connect, width=10, height=4, text=" ", command=start)
col1.grid(row=0, column=0)

connect.mainloop()
Run Code Online (Sandbox Code Playgroud)