这是一个非常奇怪的行为,因为在我的电脑上它能够正常工作:
try:
import tkinter as tk
import tkinter.ttk as ttk
except ImportError:
import Tkinter as tk
import ttk
import random
import string
def insert_something_to_combobox(box):
box['values'] = [gen_key() for _ in range(10)]
def gen_key(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
root = tk.Tk()
text_font = ('Courier New', '10')
main_frame = tk.Frame(root, bg='gray')
combo_box = ttk.Combobox(main_frame, font=text_font)
entry_box = ttk.Entry(main_frame, font=text_font)
root.option_add('*TCombobox*Listbox.font', text_font)
combo_box.pack()
entry_box.pack()
main_frame.pack()
insert_something_to_combobox(combo_box)
root.mainloop()
![下拉框](https://istack.dev59.com/5Yrk6.webp)
![输入框](https://istack.dev59.com/cClsl.webp)
对于特定的下拉框,我们可以指定一个字体,因为我们可以依赖于ttk::combobox::PopdownWindow函数:
...
class CustomBox(ttk.Combobox):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.bind('<Map>', self._handle_popdown_font)
def _handle_popdown_font(self, *args):
popdown = self.tk.eval('ttk::combobox::PopdownWindow %s' % self)
self.tk.call('%s.f.l' % popdown, 'configure', '-font', self['font'])
...
root = tk.Tk()
text_font = ('Courier New', '10')
main_frame = tk.Frame(root, bg='gray')
combo_box = CustomBox(main_frame, font=text_font)
entry_box = ttk.Entry(main_frame, font=text_font)
...
root.mainloop()
然而,这个
CustomBox
缺乏功能,因为当组合框小部件被映射时,弹出框的字体被配置了一次,因此稍后对字体的任何配置都不会为弹出框配置该选项。
让我们尝试覆盖默认的配置方法:
class CustomBox(ttk.Combobox):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._handle_popdown_font()
def _handle_popdown_font(self):
""" Handle popdown font
Note: https://github.com/nomad-software/tcltk/blob/master/dist/library/ttk/combobox.tcl#L270
"""
popdown = self.tk.eval('ttk::combobox::PopdownWindow %s' % self)
self.tk.call('%s.f.l' % popdown, 'configure', '-font', self['font'])
def configure(self, cnf=None, **kw):
"""Configure resources of a widget. Overridden!
The values for resources are specified as keyword
arguments. To get an overview about
the allowed keyword arguments call the method keys.
"""
self._configure('configure', cnf, kw)
if 'font' in kw or 'font' in cnf:
self._handle_popdown_font()
config = configure
这个类会生成一个响应更快的下拉列表实例。