【问题标题】:Trouble with Tkinter entry widgetTkinter 条目小部件的问题
【发布时间】:2012-10-22 12:07:20
【问题描述】:

我正在关注 tkinter 的介绍,特别是第 29 页上的对话框条目示例。http://www.ittc.ku.edu/~niehaus/classes/448-s04/448-standard/tkinter-intro.pdf

我收到以下错误:

d = MyDialog(root)
TypeError: this constructor takes no arguments

我从变量 d 中删除了参数,以及 wait_window 的参数(参见下面的代码),程序将运行,但是没有输入字段。

这里是代码

from Tkinter import *

class MyDialog:

    def init(self, parent):

        top = Toplevel(parent)

        Label(top, text="Value").pack()

        self.e = Entry(top)
        self.e.pack(padx=5)

        b = Button(top, text="OK", command=self.ok)
        b.pack(pady=5)

    def ok(self):
        print "value is", self.e.get()

        self.top.destroy()

root = Tk()
Button(root, text="Hello!").pack()
root.update()

d = MyDialog(root)

root.wait_window(d.top)

【问题讨论】:

    标签: python widget tkinter


    【解决方案1】:

    改变

    def init(self, parent):
    

    def __init__(self, parent):
    

    查看object.__init__的文档。

    【讨论】:

    • 嗯 ... OP 实际上并没有使用object.__init__,因为这是一个老式的类——但你是对的,它基本上做同样的事情。
    • 如果您有新问题,请将其作为新问题发布。请不要编辑您的问题以包含答案。您的原始问题已得到解答。请接受以下答案之一。
    • @Tichodroma -- 好点。每个帖子 1 个问题绝对是首选。
    【解决方案2】:

    你需要改变

    def init(self, parent):
        ... 
    

    def __init__(self, parent):
        ...
    

    (注意括号中的双下划线)。

    在 python 中,文档对构造函数的名称有点模糊,但__init__ 通常被称为构造函数(尽管有些人会争辩说这是__new__ 的工作。)。抛开语义不谈,传递给MyClass(arg1,arg2,...) 的参数将传递给__init__(前提是你不要在__new__ 中做有趣的事情,这是另一个时间的讨论)。例如:

    class MyFoo(object): #Inherit from object.  It's a good idea
        def __init__(self,foo,bar):
           self.foo = foo
           self.bar = bar
    
    my_instance = MyFoo("foo","bar")
    

    正如您的代码,由于您没有定义__init__,因此使用默认值,相当于:

    def __init__(self): pass
    

    不接受任何参数(除了强制性的self


    您还需要这样做:

    self.top = Toplevel(...)
    

    此后您尝试获取顶部属性 (d.top),但 d 没有属性 top,因为您从未添加为属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      相关资源
      最近更新 更多