如何使用 tkinter 讓 OptionMenu 保持相同的寬度?
OptionMenu 允許使用者從給定的選單項中選擇選項。要準備 OptionMenu,我們使用 OptionMenu(arguments) 建構函式,該建構函式採用父視窗小部件、用於儲存選項的變數、預設選項和可選擇的選項。
然而,在一些情況下,我們發現選項寬度與窗格寬度完全不同。我們可以透過從給定的選項中找到最大長度來保持選項的寬度。現在,透過使用 **config(width)** 方法,我們可以設定 OptionMenu 的寬度。
例項
#Import Tkinter library from tkinter import * from tkinter import ttk #Create an instance of Tkinter frame or window win= Tk() #Set the geometry of tkinter frame win.geometry("750x250") #Create Menu Items options=("Low", "Medium", "High") #Find the length of maximum character in the option menu_width = len(max(options, key=len)) #Create an OptionMenu menu=OptionMenu(win, options[0], *options) menu.config(width=menu_width) menu.pack(pady=30, ipadx=10) win.mainloop()
輸出
執行上面的程式碼將顯示一個視窗,其中包含一個選項窗格,上面有一系列選項。選項的寬度取決於給定選項中字串的最大長度。
廣告