在 child class 上使用 Toplevel 的 Tkinter 命令问题

Tkinter command problems using Toplevel on child class

尝试编写一个简单的 gui,它有多个 child classes 但顶层无法识别我用按钮上的命令设置的属性,以便它打印用户输入的任何内容在盒子里。我不知道为什么它在 child class

上不起作用
   from Tkinter import *
    import Tkinter as tk
    import tkSimpleDialog
    import tkMessageBox

    class MainWindow(tk.Frame):

        def __init__(self, *args, **kwargs):
            tk.Frame.__init__(self, *args, **kwargs)

            self.button = tk.Button(self, text="mx lookup",command=self.create_window)
            self.button.pack(side="left")





        def create_window(self):

            l = tk.Toplevel(self)
            l.entry = tk.Entry(l)
            l.button = tk.Button(l, text="search mx", command l.enter)

            l.entry.pack()
            l.button.pack()
        def enter(l):
            dns =(l.entry.get())
                  print(dns)






    if __name__ == "__main__":
        root = tk.Tk()
        main = MainWindow(root)
        main.pack(side="top", fill="both", expand=True)

        root.mainloop()

你正在设置 command l.enter 它应该是 command = self.enter

传递小部件(顶层)command = lambda: self.enter(l)或传递l.entry然后你可以调用l.get()

另外,我认为您希望 dns = l.entry.get() 打印条目小部件文本

您应该在 enter 函数的开头添加 self 作为参数来调用 self.enter 并附加一个参数,或者您可以在 class.[=16= 之外重构它]

您的代码有很多问题:

  1. 您在 command l.enter 中有错字。更正一下:command = self.enter
  2. 符号 l.entryl.button 是错误的,因为这意味着在 Python 中您已经创建了名为 entry 和 button 的属性,您现在可以使用点符号访问它们和你一样。您应该将它们重命名为其他名称。例如:l_entryl_entry.
  3. 因此 2.,在 enter() 中,您需要将 l.entry.get() 修改为 l_entry.get()
  4. 为了能够在 enter() 方法中使用 l_entry.get(),您需要在 create_window() 中写入 self.l_entry = tk.Button(self.l, text="search mx", command= self.enter),然后在 enter() 中写入 dns =(self.l_entry.get()) 而不是 dns =(l_entry.get()).

你的程序现在变成了这样:

from Tkinter import *
import Tkinter as tk
import tkSimpleDialog
import tkMessageBox

class MainWindow(tk.Frame):
   def __init__(self, *args, **kwargs):
       tk.Frame.__init__(self, *args, **kwargs)
       self.button = tk.Button(self, text="mx lookup",command=self.create_window)
       self.button.pack(side="left")

   def create_window(self):
       self.l = tk.Toplevel(self)              
       self.l_entry = tk.Entry(self.l)
       self.l_button = tk.Button(self.l, text="search mx", command= self.enter)    
       self.l_entry.pack()
       self.l_button.pack()

   def enter(self):
       dns =(self.l_entry.get())
       print(dns)

if __name__ == "__main__":
   root = tk.Tk()
   main = MainWindow(root)
   main.pack(side="top", fill="both", expand=True)
   root.mainloop()