Python Forum

Full Version: New python learner
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I jst started learnPython. Have some questions. I have a code like this to create a UI

from tkinter import Tk, BOTH
from tkinter.ttk import Frame, Label, Button, Style

class Example(Frame):

def __init__(self):
super().__init__()

self.initUI()


def initUI(self):

self.style = Style()
self.style.theme_use("default")

self.master.title("Quit button")
self.pack(fill=BOTH, expand=1)

quitButton = Button(self, text="LED",
command=self.quit)
quitButton.place(x=380, y=350)

dataLabel = Label(text="Hello, world!")
dataLabel.place(x=380, y=300)

#read data function
def readData():
ser = serial.Serial('/dev/ttyUSB0', 9600)
while True :
data = ser.readline()
print (str(data))
time.sleep(1)

ser.close()


def main():

root = Tk()
root.geometry("800x400+0+0")
app = Example()
root.mainloop()


if __name__ == '__main__':
main()
This works fine.
I have another code, reads data from serial every second:

import serial, time

ser = serial.Serial('/dev/ttyUSB0', 9600)

while True :
data = ser.readline()
print str(data)
time.sleep(1)
ser.close()
Now I need to update and display data in the label as it receiving new data. How do  that in Python? Thanks.
You need to fix your indentation.

in the ReadData __init__ method of the Example class, define:
self.data = None
then in the readData method, change:
data=ser.readline()
# to
self.data = ser.readline()
 Now self.data is visible for the entire class