简体   繁体   English

使用Tkinter在类中创建按钮

[英]Creating buttons inside a class with Tkinter

I am creating a small tkinter app in python, and need to create a large amount of buttons, that all have attributes, so I decided to create them in a class, and then create lots of instances of the class. 我正在用python创建一个小的tkinter应用程序,需要创建大量具有属性的按钮,因此我决定在一个类中创建它们,然后创建该类的许多实例。 However, because the tkinter Button is already an object, I'm not too sure how the composition between the two classes will work. 但是,由于tkinter Button已经是一个对象,因此我不太确定两个类之间的组合如何工作。 But currently, when I create an instance of my class, it seems to the the buttons command method, however will not run the command when clicked. 但是目前,当我创建类的实例时,buttons命令方法似乎没有问题,但是单击时将不会运行该命令。

Below is my module for creating buttons, which I import into my main tkinter module, and create instances of. 以下是用于创建按钮的模块,我将其导入到主tkinter模块中并创建其实例。 I wondered why the button command 'selectSeat' is run when creating the buttons, and why it doesn't run when the buttons are clicked. 我想知道为什么在创建按钮时会运行按钮命令“ selectSeat”,为什么在单击按钮时却不运行它。

from tkinter import *
class SeatButton():
    def __init__(self, master, row, seat):
    ''' Initalises a seating button '''
    self.colour = "green"
    self.state = "free"
    self.row = row
    self.seat = seat
    self.button = Button(master,bg=self.colour, command=self.selectSeat(), padx=10)


def update(self):
    ''' Updates the button's colour '''
    print("i shouldnt run")
    if self.state == "free":
        self.colour = "green"
    if self.state == "selected":
        self.colour = "blue"

def selectSeat(self):
    ''' Calculates what happens when a button is clicked'''
    # If the seat is avaliable, it is now selected
    print("hwey")
    if self.state == "free":
        self.state = "selected"
        self.colour = "blue"
    elif self.state == "selected":
        self.state == "free"
        self.colour = "green"

With command=self.selectSeat() , the function selectSeat will be executed directly (on initialization). 使用command=self.selectSeat() ,函数selectSeat将直接执行(在初始化时)。

Try passing only a reference (without braces): 尝试仅传递参考(不带花括号):

self.button = Button(master, bg=self.colour, command=self.selectSeat, padx=10)
                                                                   ^^

Tkinter will then call the function itself, see TKinter Callbacks for more examples. 然后,Tkinter将调用函数本身,有关更多示例,请参见TKinter回调

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM