如何在tkinter中使用grid()方法在新窗口小部件上创建按钮?

时间:2018-01-07 18:38:59

标签: python tkinter

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()

这是我的代码,我尝试使用grid()+ in_在新窗口小部件上创建一个按钮,但是有一个问题 - 按钮不会在新窗口小部件上创建而不是创建它在主要的一个。

1 个答案:

答案 0 :(得分:2)

tkinter窗口小部件默认情况下分配给根窗口Tk,除非将父窗口小部件作为第一个位置参数传递,在以下内容中省略:

self.new_button = tk.Button(text="Destroy", command=self.destroy)

您应该将其替换为:

self.new_button = tk.Button(parent, text="Destroy", command=self.destroy)