如何从tkinter按钮调用类函数?

时间:2020-03-26 16:48:58

标签: tkinter python-3.7

我正在尝试创建一个程序,该程序每次单击按钮时都会打印出一些东西,但是必须使用类来完成。

运行代码时,出现此错误:NameError:未定义名称'self'

(我不想将test_button放在类中,因为这只是一个更大的程序的一部分,如果我以这种方式解决问题,那么其他一些功能将无法工作。)

非常感谢任何帮助!

import tkinter as tk
from tkinter import *
window = tk.Tk()
window.geometry("500x400")
window.configure(background='grey')

class person():
    def __init__(self):
        pass

    def test(self):
        print('something')


#title label
label = tk.Label(window, text = "title",bg = '#42eff5',fg ='red',width = 35, height = 5).pack()
#button
test_button = Button(window,text='something',command = person.test(self),width= 11,height = 2,bg='blue',activebackground = 'blue',fg='white').place(x = 10,y = 30)
window.mainloop()

1 个答案:

答案 0 :(得分:1)

您需要创建人员的实例,然后在该人员上调用方法。

somebody = person()
test_button = Button(.., command=somebody.test, ...)