1

I am completely new to Python and I am using pyserial to read data from the Arduino and create a GUI using TkInter, which displays the data from the arduino in a text box of the GUI.

I am using this Python code:

from tkinter import *
from tkinter import ttk
import serial
import time

def disp():
    ser = serial.Serial('COM1', baudrate = 9600, timeout=1)
    time.sleep(1)
    arduinoData = (ser.readline().strip())
    a=arduinoData.decode('utf-8')
    dispe.delete(0,"end")
    dispe.insert(0, a)

def dis(event):
    disp()

root=Tk()
button=Button(root,text="press")
button.bind("<Button-1>",dis)
button.pack(side=LEFT)
dispe=Entry(root)
dispe.pack(side=LEFT)
root.mainloop()

This code works absolutely fine. When I click the button on the GUI it displays the values received from the Arduino. This program requires the user to click again and again to get the values, but I want to add a while loop so that I don't need to click again and again continuously.The point is to make the user click the button only once.

But when I insert a while True: loop after time.sleep to continuously update the values being received from the Arduino, nothing gets displayed on the textbox...

Saurav Saha
  • 745
  • 1
  • 11
  • 30
  • Related: [tkinter: how to use after method](https://stackoverflow.com/questions/25753632/tkinter-how-to-use-after-method) – Lafexlos Jun 19 '17 at 08:45
  • 1
    If you don't want the user to continuously click on the button, using the Button widget is the wrong way to proceed. I would simply put the while outisde the functions and call the proper function inside the aforementioned while. – David Duran Jun 19 '17 at 10:06
  • But the thing is i want the user to press the button just once, that's the whole idea – Saurav Saha Jun 19 '17 at 10:37
  • You shouldn't use infinite while loop since Tkinter already has one infinite loop. Check the linked question. `after` method is what you are looking for. – Lafexlos Jun 19 '17 at 11:33
  • Yeah thanks @Lafexlos. I used 'root.after()' worked for me instead of that infinite while loop. Now my program works absolutely fine! Thank you so much!! – Saurav Saha Jun 19 '17 at 12:00
  • and thanks to you too @David for your inputs – Saurav Saha Jun 19 '17 at 12:02

1 Answers1

0

this is the correct code :-

from tkinter import *
from tkinter import ttk
import serial
import time


def disp():

    ser = serial.Serial('COM1', baudrate = 9600, timeout=1)


    time.sleep(1)

    arduinoData = (ser.readline().strip())
    a=arduinoData.decode('utf-8')

    dispe.delete(0,"end")
    dispe.insert(0, a)
    root.after(1, disp)    

def dis(event):
    root.after(0, disp)

root=Tk()

L1 = Label(root, text="Press the button to get data from the arduino       ")
L1.pack(side=LEFT)

button=Button(root,text="press")
button.bind("<Button-1>",dis)
button.pack(side=LEFT)

dispe=Entry(root)
dispe.pack(side=LEFT)

root.mainloop()
Saurav Saha
  • 745
  • 1
  • 11
  • 30