Rao*_*eur 6 combobox tkinter ttk python-3.x
我正在尝试更改ttk Combobox的弹出列表的宽度.设置Combobox的宽度也会更改列表框的宽度,使部分值不可读.
我在Tk/Tcl中阅读了这个解决方案,但我不熟悉这种语言,并希望用Python解决这个问题.我尝试更改主题参数,但似乎没有帮助.下面是一段示例代码.
import tkinter as tk
from tkinter import ttk
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.pack()
# Trying to change the width, does not work
c.option_add("*TCombobox*Listbox*Width", 50)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
这里的任何人可以帮助我或给我一些指示?
实现菜单发布的 Tk 库文件 (ttk/combobox.tcl) 显式读取组合框小部件的宽度并将菜单顶层设置为相同的宽度(在 中ttk::combobox::PlacePopdown)。但是,您可以使用配置选项应用主题样式来覆盖它-postoffset。它的存在是为了允许某些主题抵消下拉菜单,但我们可以设置它以允许自定义宽度。注意:使用此样式的所有小部件将获得相同的宽度,因此您可能需要派生自定义样式。
在 Tcl/Tk 中,这是:ttk::style configure TCombobox -postoffset {0 0 300 0}将下拉菜单设置为 300 像素宽(xy 宽度高度)。
以下 python tkinter 代码向<Configure>事件添加一些代码以获取组合框的大小并更新宽度postoffset,以便下拉列表将与字符串列表中第一个字符串的大小相匹配。结果如下:

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()
Run Code Online (Sandbox Code Playgroud)
我们使用事件绑定来执行此操作,因为这确保我们可以获得屏幕上小部件的实际大小,以从偏移量中删除该宽度。
| 归档时间: |
|
| 查看次数: |
7554 次 |
| 最近记录: |