【问题标题】:Python - Tkinter CheckButton IssuePython - Tkinter CheckButton 问题
【发布时间】:2018-05-17 00:08:28
【问题描述】:

这是我的 GUI 程序的一部分,我遇到了问题,希望有人能帮助我。我想要做的是,当您单击检查按钮时,它应该在文本小部件上显示价格但是当我单击检查按钮时它给了我一个错误:

文件“E:\Phython\Theater.py”,第 147 行,在 update_text 中 如果 self.matinee_price.get(): AttributeError: 'Checkbutton' 对象没有属性 'get'

def matinee_pricing(self):
    #Purchase Label
    self.theater_label = tkinter.Label(text='Purchase Theater Seats Here', font=('Verdana', 15, 'bold'))
    self.theater_label.grid(row=2, column=10)
    #Checkbutton
    self.matinee_price = BooleanVar()
    self.matinee_price = tkinter.Checkbutton(text = '101 \nthru \n105', font=('Verdana', 10), bg='light pink', height=5, width=10,\
                                             variable = self.matinee_price, command = self.update_text)
    self.matinee_price.grid(row=5, column=9)

    self.result = tkinter.Text(width=10, height=1, wrap = WORD)
    self.result.grid(row=20, column=10)

def update_text(self):
    price = ''

    if self.matinee_price.get():
        price += '$50'

    self.result.delete(0.0, END)
    self.result.insert(0.0, price)

【问题讨论】:

  • 你真的不应该像那样两次导入 tkinter,这是不好的做法。请参阅this 了解更多信息。

标签: python user-interface tkinter


【解决方案1】:

您正在用复选框本身覆盖布尔变量。 BoolenaVar 的声明需要一个不同的名称,而您的其他函数需要检查该名称。

此外,复选框默认使用 0 和 1 来描述其状态。如果您想使用布尔值,您需要相应地更改 onvalueoffvalue

def matinee_pricing(self):
    # [...]
    self.matinee_price_var = BooleanVar() # Different name for the variable.
    self.matinee_price = tkinter.Checkbutton(text = '101 \nthru \n105', font=('Verdana', 10), bg='light pink', height=5, width=10,\
                                             variable = self.matinee_price_var, onvalue=True, offvalue=False, command = self.update_text)
    # Add onvalue, offvalue to explicitly set boolean states.
    # [...]

def update_text(self):
    price = ''

    # Use the variable, not the checkbox
    if self.matinee_price_var.get(): 
        price += '$50'
    #[...]

P.S.:您不需要 \ 在括号内换行。 Python 假定括号内的所有内容都是前面命令的一部分,在本例中为复选框。只需确保您没有收到任何语法错误,并且不要跨行拆分单个参数。

【讨论】:

  • 你不是也需要把variable = self.matinee_price改成variable = self.matinee_price_var吗?
  • 是的,当然,我忘了换那个。谢谢指正。
  • 谢谢!!现在工作正常。我是 python 新手,我上的这门课更像是一个研讨会而不是讲座,所以 Internet/Youtube 是我唯一的来源。
猜你喜欢
  • 2023-04-07
  • 1970-01-01
  • 2022-08-18
  • 2016-06-16
  • 1970-01-01
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 2018-10-26
相关资源
最近更新 更多