动态更改组合框大小的Python Tkinter

时间:2016-09-12 13:05:13

标签: python tkinter combobox width dynamically-generated

在Python中,Tkinter是否可以根据所选项目的长度动态更改combobox的大小(条目小部件的宽度)?

2 个答案:

答案 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)

可以使用postcommandvalidate代替使用validatecommand。这将立即生效,但有一个警告。如果组合框的大小已调整为小于其任何选择的宽度,则这些选择将被截断。例如,以我的示例为例,如果选择“奇异果”然后激活弹出窗口,您将看到:

  • 猕猴桃
  • 苹果
  • 稻草人
  • 激情f

代码:

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()