Python 如何在tkinter中使用grid()方法在新小部件上创建按钮?
这是我的代码,我正在尝试使用中的grid()+在一个新的小部件上创建一个按钮,但有一个问题-按钮不在一个新的小部件上创建,而不是在主小部件上创建。在Python 如何在tkinter中使用grid()方法在新小部件上创建按钮?,python,tkinter,Python,Tkinter,这是我的代码,我正在尝试使用中的grid()+在一个新的小部件上创建一个按钮,但有一个问题-按钮不在一个新的小部件上创建,而不是在主小部件上创建。在tkinter中,小部件默认分配给根窗口,Tk除非传递一个父窗口小部件作为第一个位置参数,该位置参数在: import tkinter as tk class Main: def __init__(self, parent): self.parent = parent self
tkinter
中,小部件默认分配给根窗口,Tk
除非传递一个父窗口小部件作为第一个位置参数,该位置参数在:
import tkinter as tk
class Main:
def __init__(self, parent):
self.parent = parent
self.button = tk.Button(text="Build", command=self.new_window)
self.button.grid(row=1, column=0)
def new_window(self):
self.window = tk.Tk()
self.app = Graph(self.window)
self.window.mainloop()
class Graph:
def __init__(self, parent):
self.parent = parent
self.new_button = tk.Button(text="text")
self.new_button.grid(in_=self.parent)
def main():
root = tk.Tk()
app = Main(root)
root.mainloop()
if __name__ == "__main__":
main()
您应将其替换为:
self.new_button = tk.Button(text="Destroy", command=self.destroy)
看起来你有一些缩进错误,感谢你更新到MCVE。我可以修复它们,因为我知道这不是问题所在,但我认为你应该为自己着想。请注意,你可以复制/粘贴代码,然后选择整个代码行并按Ctrl+K或使用
{}
查看上面的按钮,使您的代码段显示为代码。另外请注意,默认情况下,缩进级别=4个空格。
self.new_button = tk.Button(parent, text="Destroy", command=self.destroy)