__init_yu()缺少1个必需的位置参数:“widgetName”

2024-09-29 21:40:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想开发一个继承tkinter菜单类的类。这是到目前为止我的代码实现了类MyMenu,之后创建了一个测试实例mDummy,并添加了一个命令。在

# import tkinter
import tkinter as tk
# define menu class
class MyMenu(tk.Menu):
    def __init__(self, arg_master=None, **options):
    # call superclass constructors
    super(tk.Menu,self).__init__(arg_master,**options)

#define test command for menu
def testcommand():
    print("This is a test")

#start of the code    
main=tk.Tk()
mDummy=MyMenu(main)
main.config(menu=mDummy)
mDummy.add_command(label="testlabel",command=testcommand)

main.mainloop()

错误类型的执行结果:

^{pr2}$

以下是完整的回溯:

Traceback (most recent call last):   File "C:\Program Files
(x86)\Python34\MyProjects\tests\test_myUCVMenu.py", line 15, in <module>
    mDummy=MyMenu(main)   
File "C:\Program Files (x86)\Python34\MyProjects\tests\test_myUCVMenu.py", line 7, in __init__
    super(tk.Menu,self).__init__(arg_master,**options) 
TypeError: __init__() missing 1 required positional argument: 'widgetName'

从消息中,我认为tkinter menu类的__init__运算符希望我给出一个变量'widgetName'作为位置参数,但我在docu中找不到{}的含义。可能错误不是在给定的行中,而是在调用__init__运算符时代码崩溃?在


Tags: 代码testselfmasterinitmaintkinterarg
2条回答

super()需要您的小部件名称-它是MyMenu,而不是{}

 super(MyMenu, self).__init__(arg_master, **options)

事实上,以下工作:

import tkinter as tk

class MyMenu(tk.Menu):
    def __init__(self, arg_master=None, **options):
        super().__init__(arg_master,**options)

def testcommand():
    print("This is a test")

main=tk.Tk()
mDummy=MyMenu(main)
main.config(menu=mDummy)
mDummy.add_command(label="testlabel",command=testcommand)

main.mainloop()

我做了两个更正:我重新缩进了对super的调用,因此它位于__init__方法内部;并且我更改了super方法本身:python3引入了super().__init__()语法。在

对于python3.4,我需要两个更改才能使代码正常工作。在

相关问题 更多 >

    热门问题