簡體   English   中英

Tkinter 無法更新 label 文字

[英]Tkinter unable to update label text

我正在嘗試將 GPS 傳感器與 RPI 一起使用,並使用 Tkinter 制作其 GUI。 我想更新我的 GPS 值並在 GUI 中顯示。 但在 GUI 中它只顯示初始值。 在后端 GPS 值正在更新但無法在 GUI 中顯示。

import tkinter as tk
import serial
import time
import webbrowser as wb


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

class IotCar(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        width=tk.Tk.winfo_screenwidth(self)
        height=tk.Tk.winfo_screenheight(self)
        tk.Tk.geometry(self, '{}x{}'.format(width, height))


        container=tk.Frame(self)
        container.pack(side='top', fill='both', expand='True')
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = {}
        for each_frame in (StartPage, HomePage):
            frame = each_frame(container, self)
            self.frames[each_frame]=frame
            frame.grid(row=0, column=0, sticky='nsew')
        self.show_page(StartPage)

    def show_page(self, cont):

        frame=self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)
        next_button = tk.Button(self, text='Next', command=lambda:
                                controller.show_page(HomePage)).pack(side=tk.TOP,padx=5, pady=5)
class HomePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.gps_pos()
        self.lat1 = tk.StringVar()
        self.lon1=tk.StringVar(self)
        self.label_lat = tk.Label(self.HomePage, text='Latitude', justify=tk.LEFT, padx=10).pack()
        self.label_lat1 = tk.Label(self.HomePage, textvariable=self.lat1, justify=tk.LEFT,
                              borderwidth=2, relief='ridge').pack()
        self.label_lon = tk.Label(self, text='Longitude', justify=tk.LEFT, padx=10).pack()
        self.label_lon1 = tk.Label(self, text=self.lon1, justify=tk.LEFT,
                             borderwidth=2, relief='ridge').pack()

    def gps_pos(self):
        print('Entered into gps')
        ser.flushInput()
        ser.flushOutput()
        ser.write(b'AT+CGPSPWR=1\r')
        ser.write(b'AT+CGPSOUT=32\r')
        while True:
            gps=str(ser.readline())
            gps=gps[2:].split(',')
            if gps[0]=='$GPRMC' and gps[3]!='':
                lat=gps[1]
                lon=gps[1]
                break;
        self.after(3000,self.gps_pos)
        print(lat, lon)
        self.lat1.set(lat1)
app = IotCar()
app.mainloop()

請幫助我了解其中有什么問題。 先感謝您。

我無法運行此腳本,因為我沒有串行模塊,但是我修改了一些內容,這會在 label 中填充文本(代碼中的注釋)。 您需要一個 function,它將為標簽中的“文本”參數分配一個值。

import tkinter as tk
import time
import webbrowser as wb


class IotCar(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        width=tk.Tk.winfo_screenwidth(self)
        height=tk.Tk.winfo_screenheight(self)
        tk.Tk.geometry(self, '{}x{}'.format(width, height))


        container=tk.Frame(self)
        container.pack(side='top', fill='both', expand='True')
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = {}
        for each_frame in (StartPage, HomePage):
            frame = each_frame(container, self)
            self.frames[each_frame]=frame
            frame.grid(row=0, column=0, sticky='nsew')
        self.show_page(StartPage)

    def show_page(self, cont):

        frame=self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)
        next_button = tk.Button(self, text='Next', command=lambda:
                                controller.show_page(HomePage)).pack(side=tk.TOP,padx=5, pady=5)
class HomePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.lat1 = tk.StringVar()
        self.lon1 = tk.StringVar(self)
        self.label_lat = tk.Label(self, text='Latitude', justify=tk.LEFT, padx=10)
        self.label_lat.pack()

        self.label_lat1 = tk.Label(self, justify=tk.LEFT,
                              borderwidth=2, relief='ridge') # I have removed the "text" parameter because my function will update it.
        self.label_lat1.pack()

        self.label_lon = tk.Label(self, text='Longitude', justify=tk.LEFT, padx=10)
        self.label_lon.pack()
        self.label_lon1 = tk.Label(self, justify=tk.LEFT,
                             borderwidth=2, relief='ridge') # I have removed the "text" parameter because my function will update it.
        self.label_lon1.pack()
        button = tk.Button(self, text="update label", bg= "#aaaaaa", fg ="#483F44",
         font=("Arial", 10, "bold"), relief="groove", command = lambda: helloworld()) # This button will run the helloworld function
        button.pack()

        def helloworld():
            self.label_lat1["text"] = "Hello" #This will update the text parameter in label_lat1 with "Hello"
            self.label_lon1["text"] = "World" #This will update the text parameter in label_lon1 with "World"

app = IotCar()
app.mainloop()

需要注意的幾件事是將標簽與定義其參數時分開打包/放置/網格我相信您當前設置小部件的方式是給它一個 None 類型,這就是為什么您不能為其分配文本:

#You write
self.label_lat1 = tk.Label(self.HomePage, textvariable=self.lat1, justify=tk.LEFT,
                              borderwidth=2, relief='ridge').pack()

#My example
self.label_lat1 = tk.Label(self, justify=tk.LEFT,
                              borderwidth=2, relief='ridge')
self.label_lat1.pack()

You then need a command that will run a function and in that function will have a variable which will assign a text value to the label (ie the helloworld function in my code).

查看您的代碼,我相信您需要修改打包小部件的方式,然后在您的 function 中執行類似的操作

def gps_pos(self):

    print(lat, lon)
    self.label_lat1["text"] = lat 
    self.label_lon1["text"] = lon

以下是關於如何布局 tkinter gui 和其他各種常見問題的非常有用的答案。 我自己發現它非常有用在 tkinter 中的兩幀之間切換

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM