Change width of dropdown listbox of a ttk combobox

tkinter 的combobox 設定 width 來調整寬度, 解法1:
https://stackoverflow.com/questions/53785794/is-there-a-way-to-resize-the-combobox-entry-size

Combobox has a width attribute which lets you control its size. The width is in terms of the number of characters. So for example, if you know that your combobox entries are single digit numbers, you can set the width attribute as, say 1. Here is an example.

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
tList = ttk.Combobox(root, values=[1, 2, 3, 4, 5], state="readonly", width=1)
tList.current(0)
tList.grid(row=0, column=1, padx=10, pady=10)
root.mainloop()

解法2: 只調整彈出的視窗
https://stackoverflow.com/questions/39915275/change-width-of-dropdown-listbox-of-a-ttk-combobox

import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as tkfont

def on_combo_configure(event):
    global fruit
    font = tkfont.nametofont(str(event.widget.cget('font')))
    width = font.measure(fruit[0] + "0") - event.width
    style = ttk.Style()
    style.configure('TCombobox', postoffset=(0,0,width,0))

root = tk.Tk()
root.title("testing the combobox")
root.geometry('300x300+50+50')
fruit = ['apples are the best', 'bananas are better']

c = ttk.Combobox(root, values=fruit, width=10)
c.bind('<Configure>', on_combo_configure)
c.pack()

root.mainloop()

We do this using the event binding as this ensures we can get the actual size of the widget on screen to remove that width from the offset.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *