我已经定义了类 GUI,它创建了一个带有 YES 文本的按钮。 我不明白当函数是在类之外定义时应该如何将命令传递给它。
import tkinter as tk
from tkinter import ttk
import pdb
from tkinter import *
def changeButtonText():
input_bt['text'] = 'No'
input_bt['relief'] = 'sunken'
class GUI:
def __init__(self, master) -> None:
root.title('Learning TKinter')
root.resizable(False, False)
color = '#aeb3b0'
root.geometry("100x100")
root.configure(bg=color)
# Instantiating master i.e toplevel Widget
self.master = master
# Creating Button
input_bt = Button(self.master, text='Yes',width=8,command="") # how to add command 'changeButtonText' here?
input_bt.place(relx=0.1, rely=0.2)
input_bt['relief'] = 'raised'
root = tk.Tk()
gui = GUI(root)
root.mainloop() # original working place for root
基本上我想按下按钮,使其从“是”变为“否”;浮凸从凸起变为凹陷。 我需要通过类/对象来做到这一点,因为我正在尝试了解这些。 我是 Python 类对象材料的新手,希望能帮助我继续下去。
谢谢你
我尝试使用“command = self.changeButtonText”:
input_bt = Button(self.master, text='Yes',width=8,command=self.changeButtonText) # how to add command 'changeButtonText' here?
但它给了我这个错误: AttributeError:“GUI”对象没有属性“changeButtonText”
您应该将 def changeButtonText() 放在 GUI 类中
class GUI:
def __init__(self, master) -> None:
root.title('Learning TKinter')
root.resizable(False, False)
color = '#aeb3b0'
root.geometry("100x100")
root.configure(bg=color)
# Instantiating master i.e toplevel Widget
self.master = master
# Creating Button
self.input_bt = Button(self.master, text='Yes',width=8,command=self.changeButtonText)
self.input_bt.place(relx=0.1, rely=0.2)
self.input_bt['relief'] = 'raised'
def changeButtonText(self):
input_bt['text'] = 'No'
input_bt['relief'] = 'sunken'