如何在tkinter toplevel()窗口中添加按钮



当我试图在顶层添加按钮时,出现以下错误。

AttributeError: 'Toplevel' object has no attribute 'Button' 

部分代码:

def open_window():  
win=Toplevel(root)  
win.geometry("400x400")
win.title("Table Related Information")
win.grab_set() 
btn=win.Button(topframe,Text="Fetch")
btn.pack()

不能使用win.Button创建按钮,因为创建按钮不是通过Toplevel方法完成的,而是使用tkinter类完成的。正确的语法是:

win = tk.Toplevel(root)
btn = tk.Button(win, text='fetch')

其中我使用了导入语句import tkinter as tk。通过这种方式,您可以清楚地看到ToplevelButton都是属于tkinter模块的类。按钮的父级在创建时作为第一个参数。

另外,请注意text=关键字参数不应大写。

最新更新