Skip to main content
 首页 » 编程设计

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

2024年09月07日11jpfss

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_ 在新小部件上创建按钮,但存在一个问题 - 按钮不会在新小部件上创建,而是在主小部件上创建。

请您参考如下方法:

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

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

您应该将其替换为:

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