我正在嘗試制作一個不斷讀取并在 上更新的腳本,并Tkinter GUI帶有一個簡單的重繪 按鈕,但我似乎無法使其作業。我已經使用while Trueto 回圈來讀取檔案,但這不起作用,它只讀取一次,然后可能以該root.mainloop()行結尾。對我有什么解決方案嗎?
到目前為止我寫的代碼:
from tkinter import *
root = Tk()
root.geometry("400x400")
while True:
with open('door1.txt', 'r') as f:
f_contents = f.read()
f.close
def something():
global my_label
my_label.config(text=f_contents)
my_label = Label(root, text="this is my first text")
my_label.pack(pady=10)
my_buttton = Button(root, text="C",command=something)
my_buttton.pack(pady=10)
root.mainloop()
uj5u.com熱心網友回復:
洗掉while回圈,
將讀取部分放在something函式中,
洗掉f.close()因為這是背景關系管理器退出時自動執行的操作。匯入模塊時
不要使用*,匯入你需要的或者import module(其中module是你需要匯入的模塊名稱)。
您不需要使用global my_label,它已經是一個可全域訪問的名稱,并且您不會更改該名稱所指的內容。
此外,您可能希望將函式放在 GUI 部分之外,以便它們保持獨立并且代碼更具可讀性。
from tkinter import Tk, Label, Button
def something():
with open('door1.txt', 'r') as f:
f_contents = f.read()
my_label.config(text=f_contents)
root = Tk()
root.geometry("400x400")
my_label = Label(root, text="this is my first text")
my_label.pack(pady=10)
my_buttton = Button(root, text="C", command=something)
my_buttton.pack(pady=10)
root.mainloop()
uj5u.com熱心網友回復:
#try this
from tkinter import *
root = Tk()
root.geometry("400x400")
#don't change e unless you want to stop the loop
e=1
while e==1:
with open('door1.txt', 'r') as f:
f_contents = f.read()
f.close
def something():
global my_label
my_label.config(text=f_contents)
my_label = Label(root, text="this is my first text")
my_label.pack(pady=10)
my_buttton = Button(root, text="C",command=something)
my_buttton.pack(pady=10)
哦順便說一句你拼錯了按鈕
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/348457.html
