tkinter - 如何从 tkinter 按钮调用类函数?
问题描述
我正在尝试创建一个程序,每次单击按钮时都会打印一些内容,但必须使用类来完成。
当我运行我的代码时,出现此错误: 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()
解决方案
你需要创建一个人的实例,并调用那个人的方法。
somebody = person()
test_button = Button(.., command=somebody.test, ...)
推荐阅读
- macos - 为什么“last”的输出显示历史的时间少于我拥有笔记本电脑的时间?
- .net - 如何在数据表的每一列中获取大于 0 的最小字符串长度
- html - 如何将简单的计时器转换为角度 7 中的小时分钟和秒格式
- python - 在 Keras 中保存与训练运行相关的所有数据的好方法是什么?
- python - 张量流中的自定义卷积
- laravel - Laravel 路由 url 和 vuejs axious 不适用于 unicode utf-8 问题
- angular - 量角器 - 如何从多选下拉列表中选择元素
- vb.net - LINQ、加入、GroupBy 和计数
- node.js - 无法在 MongoDB 中多次保存相同的条目
- react-native - “您无权访问”错误我该怎么办?