简体   繁体   English

tkinter读取按钮状态

[英]tkinter read button state

I have a button that is normally used to print a line of data when pressed- this part works fine. 我有一个按钮,通常在按下该按钮时可以打印一行数据-该部分工作正常。 If another option (a checkbox) is on, data should be printed continuously until that button it pressed again. 如果另一个选项(复选框)处于打开状态,则应连续打印数据,直到再次按下该按钮为止。 So, I change its label to 'Stop' and wait for the button state to change from NORMAL to ACTIVE. 因此,我将其标签更改为“停止”,然后等待按钮状态从NORMAL变为ACTIVE。 However, the loop never executes. 但是,循环永远不会执行。 Here's the relevant code: 以下是相关代码:

self.read_button = Button(master, text='Read Data', command=read_data)
.
.
def read_data(self):
    if self.continuous.get()==1:
        self.read_button['text']='Stop'
        self.read_button['command']=None
        self.read_button.update_idletasks()
        # The data is never printed.
        while self.read_button['state']==NORMAL:
            print_data()
        self.read_button['text']='Read Data'
        self.read_button['command']=read_data
    else:
        print_data()

Thanks for any help. 谢谢你的帮助。 This seems simple.... 这看起来很简单。

generally speaking, Tkinter does not play nicely with while loops. 一般来说,Tkinter在while循环中表现不佳。 all of your functions need to end in a timely manner so Tkinter can tend to its tasks, like redrawing windows and checking to see if the user has clicked/typed anything. 您的所有功能都需要及时结束,以便Tkinter可以完成其任务,例如重新绘制窗口并检查用户是否单击/键入了任何内容。 If you enter an infinite loop, the UI will freeze up and stop responding to user input. 如果输入无限循环,则UI将冻结并停止响应用户输入。 If you need to continuously perform some action, you should use the after or after_idle method. 如果需要连续执行某些操作,则应使用afterafter_idle方法。

Example: 例:

from Tkinter import *

def print_data():
    print "printing data..."
    if read_button["text"] == "Stop":
        #call this again in 10 milliseconds
        root.after(10, print_data)

def read_button_clicked():
    read_button.config(command=stop_button_clicked)
    read_button.config(text="Stop")
    print_data()

def stop_button_clicked():    
    read_button.config(command=read_button_clicked)
    read_button.config(text="Read Data")

root = Tk()

read_button = Button(root, text="Read Data", command=read_button_clicked)
read_button.pack()

root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM