试图让Button更改Text小部件

时间:2015-03-03 01:56:46

标签: python python-2.7 tkinter

我有一个按钮,希望它增加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()

1 个答案:

答案 0 :(得分:1)

它挂起,因为这个while循环是无限的:

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()