Python 尝试获取按钮以更改文本小部件
我有一个按钮,希望它增加x的值,直到它为5,同时在文本框中显示其值。我不太清楚为什么它不起作用。当我运行程序时,它只是挂起Python 尝试获取按钮以更改文本小部件,python,python-2.7,tkinter,Python,Python 2.7,Tkinter,我有一个按钮,希望它增加x的值,直到它为5,同时在文本框中显示其值。我不太清楚为什么它不起作用。当我运行程序时,它只是挂起 from Tkinter import * root = Tk() mybutton = Button(root,text="Push me to increase x!") mybutton.pack() text =
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()
从Tkinter导入*
root=Tk()
mybutton=按钮(root,text=“按我增加x!”)
mybutton.pack()
text=文本(根)
text.insert(插入“Hello!”)
text.pack()
x=0
def max():
text.insert(结束,“x太大了!”)
def show():
文本。插入(结束,“x是”,x)
x+=1
当x<6时:
mybutton.configure(命令=show)
mybutton.configure(命令=max)
root.mainloop()
由于此while循环不正确,因此挂起:
while x < 6:
mybutton.configure(command=show)
它不运行使用
x+=1
语句的show
函数吗?GUI开发是事件驱动的,程序的“动作”不会以“正常”顺序出现。因此,您的show
功能必须仅在对单击按钮事件的响应中执行。该事件触发/调用show函数,该函数递增x,而不是while循环。这里mybutton.configure(command=show)
您只需告诉Tk,该显示应该作为按钮单击的结果执行。这本身并不是所谓的优先权,我想我会遵循。所以按钮按下只能绑定到一个函数,但我可以让该函数根据特定条件考虑不同的路径,就像您在if
语句中所做的那样?是的。在“show”功能中,你可以做任何你想做的事情。您可以获得有关格式的信息。
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()