在其他帖子中找不到我的問題的確切答案。我正在尋找的是在我的其他功能運行時更新我的??標簽的方法。我嘗試先更改標簽,然后呼叫 my_function(),但標簽仍然沒有更新,但是 my_function() 正在運行并在終端中列印結果。我對 Tkinter 完全陌生,據我所知,雖然我們沒有點擊 window.mainloop() 我的標簽不會更新。在其他功能運行時是否有任何方法可以更新標簽?
import os
import tkinter as tk
from tkinter import END, Label, Scrollbar, Text, filedialog
def my_function(directory: str) -> None:
for item in os.scandir(directory):
if item.is_file:
# print(f'File name: {item.name}')
text_area.insert(END, f'File name: {item.name}\n')
def select_folder() -> None:
'''
Tkinter function for button,
user can select folder.
'''
path = filedialog.askdirectory()
status.config(text='Status: Work in progress, please wait!')
text_area.insert(END, 'Visited folders:\n')
my_function(path)
status.config(text='Status: Done!')
# Start the app window
window = tk.Tk()
window.title('PDF maker')
window.geometry('400x400')
# Status Label
status = Label(window, text='Status: Select the folder')
status.pack()
# Button for selecting folder
button = tk.Button(window, text='Select Folder', command=select_folder)
button.pack(side='bottom', pady=30)
# Horizontal and Vertical Scrollbars
v_s = Scrollbar(window)
v_s.pack(side='right', fill='y')
h_s = Scrollbar(window, orient='horizontal')
h_s.pack(side='bottom', fill='x')
# Text area for result output
text_area = Text(
window,
wrap='none',
font=('Times New Roman', 13),
yscrollcommand=v_s.set,
xscrollcommand=h_s.set
)
text_area.pack(padx=10, pady=10, expand=True, fill='both')
# Adding scrollability to text
v_s.config(command=text_area.yview)
h_s.config(command=text_area.xview)
window.mainloop()
更新
還是應該為一個按鈕創建 2 個功能?第一個函式將更改標簽和文本,第二個函式將運行 my_func()。
uj5u.com熱心網友回復:
通常,答案很簡單。
嘗試這個:
#...
def select_folder() -> None:
"""
Tkinter function for button,
user can select folder.
"""
status.config(text="Status: Work in progress, please wait!") # switched lines here
path = filedialog.askdirectory()
text_area.insert(END, "Visited folders:\n")
my_function(path)
status.config(text="Status: Done!")
#...
以前它沒有按預期作業,因為filedialog.askdirectory()阻塞了程式流(類似于input())。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/452606.html
