【问题标题】:How to call a class function from a tkinter button?如何从 tkinter 按钮调用类函数?
【发布时间】:2020-03-26 16:48:58
【问题描述】:

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

当我运行我的代码时,我得到这个错误:NameError: name 'self' is not defined

(我不想将 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()

【问题讨论】:

    标签: tkinter python-3.7


    【解决方案1】:

    你需要创建一个人的实例,然后调用那个人的方法。

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

    【讨论】:

    • 我之前尝试过,而不是运行特定函数,在这种情况下,测试函数运行整个类
    • 哦,别管我的坏,它可以工作,还有另一个错误导致了这个错误。
    猜你喜欢
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2019-06-23
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多