首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OptionMenu修改下拉列表宽度以匹配OptionMenu宽度

OptionMenu修改下拉列表宽度以匹配OptionMenu宽度
EN

Stack Overflow用户
提问于 2015-10-27 11:59:02
回答 1查看 2.3K关注 0票数 1

现在我明白了,Python Tkinter: OptionMenu modify dropdown list width已经有了一个类似的问题,但是这对我没有帮助。

我试图使下拉菜单的宽度从OptionMenu小部件响应。这意味着宽度将始终与OptionMenu的宽度匹配。如下面的代码所示,我尝试了一些东西,但它们不适用于子菜单,它将始终保持在固定的宽度。没有办法改变吗?

代码语言:javascript
复制
import tkinter as tk

root = tk.Tk()

var = tk.StringVar()
var.set('First')

option = tk.OptionMenu(root, var, 'First', 'Second', 'Third')
option.configure(indicatoron = False)

option.pack(expand = True, fill = tk.X)

# Sub-menu config
submenu = option['menu']
submenu.configure(width = 50) # Can't use width
submenu.pack_configure(expand = True, fill = tk.X) # Can't use pack_configure

root.mainloop()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-27 19:21:09

虽然没有方法显式地设置宽度,但是如果真正的必须使用tkinter,那么就可以添加黑客解决方案来消除这些问题。这方面的例子是:

代码语言:javascript
复制
import tkinter as tk
from tkinter import font as tkFont

def resizer(event=None):
    print("Resize")
    widget = event.widget
    menu = widget['menu']

    req_width = widget.winfo_width()-10
    menu_width = menu.winfo_reqwidth()

    cur_label = menu.entrycget(0, "label")
    cur_label = cur_label.rstrip() # strip off existing whitespace

    font = tkFont.Font() # set font size/family here
    resized = False
    while not resized:
        difsize = req_width - menu_width # check how much we need to add in pixels
        tempsize = 0
        tempstr = ""
        while  tempsize < difsize:
            tempstr += " " # add spaces into a string one by one
            tempsize = font.measure(tempstr) #measure until big enough
        menu.entryconfigure(0, label=cur_label + tempstr) # reconfigure label
        widget.update_idletasks() # we have to update to get the new size
        menu_width = menu.winfo_reqwidth() # check if big enough
        cur_label = menu.entrycget(0, "label") # get the current label for if loop needs to repeat
        if menu_width >= req_width: # exit loop if big enough
            resized = True

root = tk.Tk()

var = tk.StringVar()
var.set('First')

option = tk.OptionMenu(root, var, 'First', 'Second', 'Third')
option.bind("<Configure>", resizer) # every time the button is resized then resize the menu
option.configure(indicatoron = False)

option.pack(expand = True, fill = tk.X)

root.mainloop()

从本质上说,这只是在菜单足够大之前将第一个菜单项删除。然而,似乎确实有一些差距的宽度报告回来,因此我的req_width = widget.winfo_width()-10偏移接近顶部。

然而,这并不总是一个完美的匹配大小,而测试我的a空间似乎需要3个像素的宽度,因此它可能是1或2个像素在任何时候。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33367443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档