Tkinter使用grid布局时报错问题(附相关代码)
解决Tkinter中
cannot use geometry manager grid inside . which already has slaves managed by pack错误 错误原因
Tkinter有个硬性规则:同一个父容器内,绝对不能同时混用pack和grid两种布局管理器。你代码里的根窗口root已经通过pack()添加了ttl标签、text文本框、button_frame框架这三个组件,却又直接把arial按钮用grid()布局到root里,两种布局在同一个父容器冲突,触发了这个错误。
修正方案
把按钮放到你已经创建好的button_frame框架中,框架内部可以单独使用grid布局,框架本身通过pack()放到根窗口,这样就不会和根窗口的其他pack布局组件冲突了。
修改后的完整代码
import tkinter as tk root = tk.Tk() fnt = 'Arial' root.title('Text Editor') root.geometry('800x500') ttl = tk.Label(root, text='Text Editor', font=('Arial', 25), height=3) ttl.pack(padx=10, pady=20) text = tk.Text(root, font=(fnt, 16)) text.pack(padx=0, pady = 10) button_frame = tk.Frame(root) button_frame.columnconfigure(0, weight=1) button_frame.columnconfigure(1, weight=1) button_frame.columnconfigure(2, weight=1) # 将按钮的父容器改为button_frame,而非root arial = tk.Button(button_frame, text='Arial', font=('Arial',10), height=1) arial.grid(row=0, column=0, sticky=tk.W+tk.E) button_frame.pack(fill='x') root.mainloop()
内容的提问来源于stack exchange,提问作者BackOut
相关产品推荐
相关产品推荐

