在Python中,Tkinter是否可以根据所选项目的长度动态更改combobox
的大小(条目小部件的宽度)?
答案 0 :(得分:0)
这就是你要找的东西:
from tkinter import *
import ttk
root = Tk()
defaultCar = StringVar()
defaultCar.set("Mercedes Benz")
carList = ["BMW", "Lamborghini", "Honda"]
def resizeFunc():
newLen = len(cars.get())
cars.configure(width=newLen+2)
cars = ttk.Combobox(root,
textvariable=defaultCar,
values=carList,
postcommand=resizeFunc)
cars.pack()
答案 1 :(得分:0)
可以使用postcommand
和validate
代替使用validatecommand
。这将立即生效,但有一个警告。如果组合框的大小已调整为小于其任何选择的宽度,则这些选择将被截断。例如,以我的示例为例,如果选择“奇异果”然后激活弹出窗口,您将看到:
代码:
from tkinter import Tk
from tkinter.ttk import Combobox
class Application(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
items = ["kiwi", "apple", "strawberry", "passion fruit"]
kws = dict(
values = items,
validate = "focus",
state = "readonly",
validatecommand = self.resize
)
self.cb = Combobox(self, **kws)
self.cb.set(items[0])
self.cb.pack(anchor="nw")
self.resize()
def resize(self):
self.cb.configure(width=len(self.cb.get())+1)
return True #must return True
if __name__ == "__main__":
app = Application()
app.minsize(800, 600)
app.title("My Application")
app.mainloop()