【问题标题】:Creating buttons inside a class with Tkinter使用 Tkinter 在类中创建按钮
【发布时间】:2019-07-03 11:46:46
【问题描述】:

我在 python 中创建一个小的 tkinter 应用程序,并且需要创建大量的按钮,它们都有属性,所以我决定在一个类中创建它们,然后创建该类的许多实例。但是,因为 tkinter Button 已经是一个对象,所以我不太确定这两个类之间的组合将如何工作。但是目前,当我创建我的类的实例时,似乎是按钮命令方法,但是单击时不会运行命令。

下面是我用于创建按钮的模块,我将其导入到我的主 tkinter 模块中,并创建其实例。我想知道为什么在创建按钮时会运行按钮命令“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"

【问题讨论】:

  • 您是在 'command=self.selectSeat()' 中直接调用该方法。只需使用 'command=self.selectSeat'

标签: python tkinter


【解决方案1】:

使用command=self.selectSeat(),将直接执行函数selectSeat(在初始化时)。

尝试只传递一个引用(不带大括号):

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

Tkinter 然后会调用函数本身,更多示例请参见TKinter Callbacks

【讨论】:

  • 听起来不错,谢谢,如果没有参数,您将如何传递变量等?
  • 你试过扩展 Tkinter 按钮吗?像 class SeatButton(Button) 而不是 self.button 属性。
猜你喜欢
  • 1970-01-01
  • 2016-07-31
  • 2021-06-02
  • 2016-04-28
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 2021-01-16
  • 1970-01-01
相关资源
最近更新 更多