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

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

最佳答案

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

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

您应该将其替换为:

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

关于python - 如何在 tkinter 中使用 grid() 方法在新小部件上创建按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48140347/

相关文章:

python - 错误: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\resize.cpp:4045: error: (-215:Assertion failed)

python - AbstractBaseUser 电子邮件作为用户名验证

python - 如何在基于 Django 类的 View 中访问当前用户

python - 如何在 Tkinter 中实现不确定的进度条?

python - Tkinter 中的 validatecommand — 循环验证?

python - 如何使用 askopenfilename 从浏览按钮检索文件路径并使用 Tkinter 将其写入条目小部件

python - 使用 Google 协作中的所有可用 RAM 后,您的 session 崩溃

python - 如何在 Tkinter 小部件中获取 cmd

python - 如何让 tkinter 使用 Ubuntu 的默认 Python 2.7 安装?

python - PyCharm 导入错误 : No module named googleapiclient