1 回答

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超8個(gè)贊
您需要調(diào)整代碼以與 GUI 配合使用。您無(wú)法在 tkinter GUI 中引入無(wú)限循環(huán)而不引起各種問(wèn)題。
Mainloop 應(yīng)該只被調(diào)用一次。
我建議您將所有掃描/保存操作移至一個(gè)單獨(dú)的函數(shù)中,您計(jì)劃使用 tkinterafter方法定期執(zhí)行該函數(shù)。
例如,如果您調(diào)用函數(shù),scan您可以使用以下命令將其安排在 1 秒后發(fā)生
root.after(1000, scan)
更高級(jí)的方法是讓掃描代碼在單獨(dú)的線(xiàn)程上運(yùn)行。
此外,您當(dāng)前嘗試在每次循環(huán) while 循環(huán)時(shí)創(chuàng)建標(biāo)簽,而不是僅創(chuàng)建和打包它們一次并在執(zhí)行“掃描”時(shí)更新標(biāo)簽的文本。您可以使用 config 方法更新標(biāo)簽的文本,例如
## Create a label
label1 = tk.Label(window,text = "PAKAVIMO OPERACIJA:")
##Pack the label
label1.pack()
## Update the text later
label1.config(text="New Text")
以下是從函數(shù)定期更新 tkinter 小部件的示例。
import tkinter as tk
import random
def scanning():
num = random.randint(0,100)
entryTemperature.delete(0, tk.END) #Delete the current contents
entryTemperature.insert(0, f"{num} K") #Add new text
root.after(1000, scanning) #Schedule the function to run again in 1000ms (1 second)
root = tk.Tk()
entryTemperature = tk.Entry(root)
entryTemperature.grid(padx=50,pady=50)
root.after(1000, scanning)
root.mainloop()
添加回答
舉報(bào)