简体   繁体   中英

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. 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. 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. If you enter an infinite loop, the UI will freeze up and stop responding to user input. If you need to continuously perform some action, you should use the after or after_idle method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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