我之前嘗試過問這個問題,但我認為這是一個更好的提問方式。
開始:
我正在使用 Windows 和 Python 3,帶有Tkinter.
我試圖在按下按鈕時更新我的??網格的第一行,即page_label隨著時間的推移添加一個字符,我目前正在嘗試time.sleep()在for回圈中使用它。
在沒有 gui 的情況下使用時效果非常好sys.stdout.write(),但我無法直接將任何內容寫入標簽,而不是我的終端。
所以,我想我應該能夠使用.configfrom tkinter,并且只更新每個字符的標簽,每次更新之間有一小段時間延遲。
但是,當我運行以下代碼時,時間延遲堆疊并且對配置的更新直到最后才會運行。
所以,當我第一次運行應用程式時,我會在page_label. 然后在我假設for回圈完成之后,最終的新陳述句顯示為標簽更新。
我會很高興我目前的解決方法可以作業,或者如果有一種很好、干凈的方式可以stdout直接寫入標簽,我會非常高興。
import time
from tkinter import *
from tkinter.ttk import *
from PIL import Image, ImageFont, ImageTk, ImageDraw
import json
root = Tk()
root.title('actiread test')
root.iconbitmap("C:\\Users\\nicho\\Desktop\\Code Puzzles\\actiread\\actireadico.ico")
root.geometry("800x800")
#button triggering time delay text
def get_input():
words = ""
statement = "I need this to print in time delay"
for char in statement:
words = words char
page_label.config(text = words)
time.sleep(0.2)
#creating updating label
page_label = Label(root, text = "I want to start with an introduction")
#creating button
entry_button = Button(root, text = "Start", command = get_input)
page_label.grid(row = 0, column = 0, columnspan = 2)
entry_button.grid(row = 1, column = 0, pady = 10, sticky = EW)
root.mainloop()
請忽略無用的匯入,我有更多內容要添加到我認為需要它們的程式中。
如果它有幫助,我想要完成的最終將需要用戶輸入,這些輸入將被保存以供以后使用,我將通過幾個版本來移動故事情節。
蒂亞!
uj5u.com熱心網友回復:
問題是,當您使用時time.sleep(),它會阻止 tkinter 事件回圈處理事件,并且您的 GUI 由于無法處理事件而被卡住。正確的方法是使用root.after(ms, func, *args)在給定時間后重復功能的方法。
def get_input(words="",count=0):
statement = "I need this to print in time delay"
if count < len(statement):
words = statement[count] # Index and get the current letter and add to the current string
page_label.config(text=words)
count = 1
root.after(200,get_input,words,count) # Call the function passing arguments words and count
另一種解決方法是root.update在 for 回圈中使用來強制 tkinter 處理事件,但這不是一個好習慣。
一個相對簡單的解決方案可能是使用全域變數來更好地理解:
count = 0
words = ""
def get_input():
global count, words
statement = "I need this to print in time delay"
if count < len(statement):
words = statement[count]
page_label.config(text = words)
count = 1
root.after(200,get_input)
請注意,傳遞的 200 是以毫秒為單位的延遲時間,與傳遞的 0.2 秒相同time.sleep
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465729.html
