我正在尝试将Optionmenu与中心和并排对齐,但每当我取消注释.grid()
语句时,窗口中都不会显示任何内容。
import tkinter as tk
from utils import editionMap, topicMap, langMap
class OptionMenu(tk.Frame):
def __init__(self, master, status, *options):
self.frame = tk.Frame(master)
self.frame.pack()
self.status = tk.StringVar()
self.status.set(status)
self.dropdown = tk.OptionMenu(self.frame, self.status, *options)
self.dropdown.pack()
def main():
root = tk.Tk()
Edition_Filter = OptionMenu(root, "Edition", *editionMap.keys())
#Edition_Filter.grid(row=0, column=0) <---Uncomment
Language_Filter = OptionMenu(root, "Language", *langMap.keys())
#Language_Filter.grid(row=0, column=1) <---Uncomment
Topic_Filter = OptionMenu(root, "Topic", *topicMap.keys())
#Topic_Filter.grid(row=0, column=2) <---Uncomment
root.mainloop()
if __name__ == '__main__':
main()
我想将显示选项菜单水平并排Edition Language Topic
。
我的实际输出是:
答案 0 :(得分:1)
你混合了两种不同的技术
第一:继承
class OptionMenu(tk.Frame): # <-- with Frame
def __init__(self, master, status, *options):
super().__init__(master) # <-- with super()
第二:包括
class OptionMenu(): # <-- without Frame
def __init__(self, master, status, *options):
self.frame = tk.Frame(master) # <-- create inner widget
首先创建可以使用menu.pack()
或menu.grid()
第二个不创建窗口小部件 - 它创建了里面有窗口小部件的普通类,你必须使用menu.frame.pack()
或menu.frame.grid()
真实小部件的示例
import tkinter as tk
class OptionMenu(tk.Frame): # <-- with Frame
def __init__(self, master, status, *options):
super().__init__(master) # <-- with super()
self.status = tk.StringVar()
self.status.set(status)
# use `self` as parent for widgets inside
self.dropdown = tk.OptionMenu(self, self.status, *options)
self.dropdown.pack()
def main():
editionMap = {1:"English", 2:"German", 3:"Russian"}
langMap = {1:"English", 2:"German", 3:"Russian"}
topicMap = {1:"English", 2:"German", 3:"Russian"}
root = tk.Tk()
Edition_Filter = OptionMenu(root, "Edition", *editionMap.keys())
Edition_Filter.grid(row=0, column=0)
Language_Filter = OptionMenu(root, "Language", *langMap.keys())
Language_Filter.grid(row=0, column=1)
Topic_Filter = OptionMenu(root, "Topic", *topicMap.keys())
Topic_Filter.grid(row=0, column=2)
root.mainloop()
if __name__ == '__main__':
main()