简体   繁体   中英

Tkinter freezes when i use after command?

I'm making a Python script that will enable me to comunicate with a arduino and i have astabished comunication, but i whant to create a nice GUI using Tkinter. I have made a code that will sets this but it frezzes so that i ca't press any buttons before i have given a serial input to the Python script. Wonse i give the script a input it unfreezes and i can use it. but i dont whant to have to send a serial input to be able to unfreeze the GUI. There must be a better way?! I'm using Python 3.4.

My current code:

from tkinter import *
import serial, os, time

ser = serial.Serial("/dev/ttyACM0", 9600)

root = Tk()
root.geometry("300x300")

def onled():
    ser.write(b'1')
    ledstate.config(text="Led is: On")

def offled():
    ser.write(b'2')
    ledstate.config(text="Led is: Off")

switchstate =Label(root, text="Switch is: Off")
switchstate.place(x=10, y=3)

ledon = Button(root, text="ON", command=onled)
ledon.place(x=100, y=16)
ledoff = Button(root, text="OFF", command=offled)
ledoff.place(x=150, y=16)

ledstate = Label(root, text="Led is: Off")
ledstate.place(x=10, y=20)

def head():
    serialInput = ser.readline()
    print(serialInput)
    if serialInput == b'1001\r\n':
        switchstate.configure(text="Switch is: On")
    if serialInput == b'1002\r\n':
        switchstate.configure(text="Switch is: Off")
    root.update_idletasks()
    root.after(1000, head)

root.after(1000, head)
root.mainloop()

Thanks!

Tkinter is single-threaded. If ser.readline() blocks while waiting for data to read, then yes, the GUI will freeze. If that is the case, you will need to either make it non-blocking, or do the read in another thread and communicate the data back to the GUI with a thread-safe queue.

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