Tkinter 中 "update" 和 "update_idletasks" 有什麼區別?


update 方法處理所有掛起的空閒任務、未訪問的事件、呼叫函式和回撥函式。該方法適用於更新和處理所有事件或任務,例如重繪小部件、幾何管理、配置小部件屬性等。

它還確保如果應用程式有任何掛起的任務,則它只會更新或重新整理影響應用程式整個部分的值。對於單個掛起任務使用update 會很糟糕,因此 Tkinter 還提供了update_idletasks() 方法。它只更新應用程式中由於某種原因而處於穩定狀態或未更新的空閒掛起任務。它會呼叫所有掛起的事件,而不會處理任何其他事件或回撥函式。

update() 和 update_idletask() 方法可用於處理任何掛起或空閒任務。但是,update()update_idletasks() 之間的唯一區別在於,update() 處理應用程式中存在的所有事件,而 update_idletasks() 只處理那些未執行或處於穩定狀態的事件。

示例

我們可以透過這個例子瞭解update_idletasks() 方法的用法和應用。

# Import the tkinter library
from tkinter import *
from tkinter import ttk
import time

# Create an instance of tkinter frame
win= Tk()

# Set the size of the Tkinter window
win.geometry("700x350")
def add_Text():
   for i in range(10):
      label.config(text= "The loops starts from 1 to "+ str(i))
      # Wait for two seconds
      win.update_idletasks()
      time.sleep(2)
      label.config(text= i)

# Add a label text
label= Label(win, text="Original Text", font= ('Aerial 16'))
label.pack(pady= 30)

# Add a button to update the Label text
ttk.Button(win, text="Change Text", command= add_Text).pack(pady= 40)
win.mainloop()

輸出

執行以上程式碼將顯示一個帶有標籤小部件和按鈕的視窗。

當我們按下按鈕時,標籤小部件在給定的迴圈範圍內自動更新。

更新於: 2021年6月7日

10K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.