试图获取一个按钮来更改文本小部件

Trying to get a Button to change a Text widget

我有一个按钮,希望它增加 x 的值直到它是 5,同时在文本框中显示它的值。我不太确定为什么它不起作用。当我 运行 程序挂起时。

from Tkinter import *
root = Tk()  
mybutton = Button(root,text="Push me to increase x!")                                     
mybutton.pack()                                     

text = Text(root)
text.insert(INSERT, "Hello!")
text.pack()

x = 0

def max():
    text.insert(END, "x is too big!")

def show():
    text.insert(END, "x is ", x)
    x += 1

while x < 6:
    mybutton.configure(command=show)
mybutton.configure(command=max)

root.mainloop()

它挂起是因为这个 while 循环是 infnit:

while x < 6:
    mybutton.configure(command=show)

您在这里没有增加 x 的值。所以它永远不会达到 6。我认为你最后是在追求这样的东西:

from Tkinter import *


root = Tk()  
mybutton = Button(root,text="Push me to increase x!")                                     
mybutton.pack()                                     

text = Text(root)
text.insert(INSERT, "Hello!")
text.pack()

x = 0

def max():
    text.insert(END, "\nx is too big!")

def show():
    global x

    if x  == 6:
        max()
        return

    text.insert(END, "\nx is {}".format(x))
    x += 1



mybutton.configure(command=show)


root.mainloop()