Python Tkinter: OptionMenu modify dropdown list width

安稳与你 提交于 2019-12-05 18:18:37

There is no way to change the width of the dropdown.

You might want to consider the ttk.Combobox widget. It has a different look that might be what you're looking for.

One idea is to pad the right side (or left, or both) with spaces. Then, when you need the selected value, strip it with str strip. Not great, but better than nothing.

from tkinter import ttk
import tkinter as tk

root = tk.Tk()

def func(selected_item):
  print(repr(selected_item.strip()))

max_len = 38
omvar = tk.StringVar()
choices = ['Default Choice', 'whoa', 'this is a bit longer'] + ['choice'+str(i) for i in range(3)]
padded_choices = [x+' '*(max_len-len(x)) for x in choices]
om = ttk.OptionMenu(root, omvar, 'Default Choice', *padded_choices, command=func)
om.config(width=30)
om.grid(row=0, column=0, padx=20, pady=20, sticky='nsew')

root.mainloop()
Sreenidhi D R

We can change the dropdown width by writing as follows:

typesOfSurgeries = ['Chemotherapy','Cataract']
listOfSurgeries = tkinter.OptionMenu(test_frame, variable, *typesofSurgeries)
listOfSurgeries.config(width=20)
listOfSurgeries.grid(row=14,column=1)

listOfSurgeries.config(width=20) sets the width of the OptionMenu

This is old, but hopefully the answer is still helpful.

the sticky options of N S W E are part of the tkinter package. So they should not be in quotations. Try

typeOption.grid(column = 0, columnspan = 2, row = 0, sticky = N+S+W+E, padx = 5, pady = 5)

Which is more obvious if instead of "from tkinter import *" you had

import tkinter as tk
typeOption.grid(column = 0, columnspan = 2, row = 0, sticky = tk.N+tk.S+tk.W+tk.E, padx = 5, pady = 5)

Then just make sure the column isn't shrinking by working with minsize in the frame's columnconfigure function.

**Note there are other combinations of parameters also built in to tkinter like NSEW but not NSWE

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!