0

I am beginner in the field of Tkinter. I have a small task to create a GUI with Tkinter. I just need few buttons like Read data and stop Read data and quit. Here the data comes over serial port.

I have created the code. My idea is when I click on Read data button it should go to while loop and there it has to read the data and print them on the GUI. When I click stop Read data it should stop reading it.

However, when I click on Read data button it is going to while loop and GUI is hanging there. I am unable to click any button and also I can not see the data.

Here is my code:

import tkinter as tk
import serial,time
import datetime
import array as arr

addr = "COM10" ## serial port to read data from
baud = 115200 ## baud rate for instrument
ser = serial.Serial(
    port = addr,\
    baudrate = baud,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
    timeout=1)


class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.appName = tk.Button(self,fg="red", bg="blue")
        self.appName["text"] = "SCAN "
        self.appName.pack(side="top")
        

        self.startScanBtn = tk.Button(self,fg="red", bg="green")
        self.startScanBtn["text"] = "Start Scanning "
        self.startScanBtn["command"] = self.scan
        self.startScanBtn.pack(side="left")
        

        self.stopScanBtn = tk.Button(self,fg="black", bg="red")
        self.stopScanBtn["text"] = "Stop Scanning "
        self.stopScanBtn.pack(side="right")
        
        
        self.quit = tk.Button(self, text="QUIT", fg="red",
                              command=self.master.destroy)
        self.quit.pack(side="bottom")
        
    def scan(self):
        while(true):
            c = ser.readline() # attempt to read a character from Serial
            line = c.decode('utf-8').replace('\r\n', '')
            tk.Label(self,text = line).pack()        
root = tk.Tk()
app = Application(master=root)
app.mainloop()

1 Answer 1

1

the reason your GUI becomes unresponsive is because python is busy in the while loop. You may want to consider using multithreading to use your scan function in a different thread, threading.thread would be a good place to start. Then you would need to send data from the scan thread to the main thread to display in the GUI, PySubPub can help with this. Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.