我在讓這些功能為我的 tkinter 應用程式正常作業時遇到一些問題。我有兩個檔案,一個包含主 Window 類,另一個包含我試圖連接到按鈕命令的函式。問題是按鈕在主視窗中,我與其“點擊”關聯的功能沒有更新,似乎只是執行了一次。
這是我的兩個檔案: main.py
import customtkinter as ctk
from size import *
class Window(ctk.CTk):
WIDTH = 700
HEIGHT = 600
def __init__(self) -> None:
super().__init__()
self.geometry(f"{Window.WIDTH}x{Window.HEIGHT}")
self.title("Test")
#Setup Frames-----#
#Configure grid layout (2x1)
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(0, weight=1)
#Configure left frame
self.frame_left = ctk.CTkFrame(master=self,width=180,corner_radius=0)
self.frame_left.grid(row=0, column=0, sticky="nswe", padx=10,pady=10)
#Configure right frame
self.frame_right = ctk.CTkFrame(master=self)
self.frame_right.grid(row=0, column=1, sticky="nswe", padx=10, pady=10)
#Far Left Frame
self.frame_left.grid_rowconfigure(0, minsize=10)
#Labels-----#
#Left Frame Labels
size_label = ctk.CTkLabel(master=self.frame_left, text="Size Option:")
monster_name_label = ctk.CTkLabel(master=self.frame_left, text="Monster Name:")
#Right Frame Labels
display_monster_name = ctk.CTkLabel(master=self.frame_right, text='')
display_size = ctk.CTkLabel(master=self.frame_right, text='')
#Comboboxes-----#
#Size
size_combobox = ctk.CTkComboBox(master=self.frame_left, values=size_options_combobox)
size_combobox.set("Random")
#Functions-----#
#Size
size_command = add_size(size_combobox, display_size)
#Buttons-----#
#Size
add_size_btn = ctk.CTkButton(master=self.frame_left,command=size_command, text=" ", width=30)
#Grid Layout-----#
#Left frame grid layout
#Row 1
size_label.grid(row=1, column=0)
size_combobox.grid(row=1, column=1)
add_size_btn.grid(row=1, column=2, sticky = "W")
#Right frame grid layout
#Row 1
display_size.grid(row=1,column=1)
if __name__ == "__main__":
window = Window()
window.mainloop()
我從中匯入的另一個檔案是 size.py:
from main import *
import customtkinter as ctk
import random
def add_size(size_combobox, display_size):
size_choice = StringVar()
size_choice = size_combobox.get() #Suspect this maybe the issue
random_size = random.choice(size_options_label)
if size_choice == "Random":
display_size['text'] = random_size
else:
display_size['text'] = size_choice
我懷疑問題可能出在 add_size 函式的 .get() 呼叫上,因為如果我在 Window 類的 main.py 中運行它,它會作業并使用組合框選項更新 Labels 值。
這是它運行一次時的螢屏截圖,由于它設定為“隨機”,因此 if 陳述句以它的值執行一次,并且在單擊另一個按鈕后不會更新。

uj5u.com熱心網友回復:
您明確要求add_size在此行中呼叫:
size_command = add_size(size_combobox, display_size)
您需要將其更改為使用 lambda 或 functools.partial:
size_command = lambda: add_size(size_combobox, display_size)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497233.html
