问题
I have created an OptionMenu from Tkinter with a columnspan of 2. However, the dropdown list/menu does not match the width, so it does not look good. Any idea on how to match their width?
self.widgetVar = StringVar(self.top)
choices = ['', 'wire', 'register']
typeOption = OptionMenu(self.top, self.widgetVar, *choices)
typeOption.grid(column = 0, columnspan = 2, row = 0, sticky = 'NSWE', padx = 5, pady = 5)
回答1:
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.
回答2:
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()
回答3:
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
回答4:
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
来源:https://stackoverflow.com/questions/26000571/python-tkinter-optionmenu-modify-dropdown-list-width