【问题标题】:How do I properly change the values of a Radiobutton?如何正确更改 Radiobutton 的值?
【发布时间】:2015-09-07 01:38:36
【问题描述】:

我创建了一个 IntVar() this.v。 当 this.v = 1 时,我的 elif 语句为真,不应该是这样。 我做错了什么? 当我 print(this.v.get()) 返回的值为 1。 (导入 tkinter)

this.v = IntVar()
this.button1 = Radiobutton(this.root,text = "Small Boxes First",variable = this.v,value = 1)
this.button1.grid(row = 2,column = 5)
this.button2 = Radiobutton(this.root,text = "Large Boxes First",variable = this.v,value = 2)
this.button2.grid(row = 3,column = 5)

def packNSaveClicked(this):
        if(int(this.wid.get()) <= 0 or int(this.len.get()) <= 0 or this.len.get() == '' or this.wid.get() == ''):
            messagebox.showerror("Truck Size Error", "The length or width of the Truck is not a valid value!")
        elif(int(this.v.get()) != 1 or int(this.v.get()) != 2):
           #ALWAYS SHOWING UP, even though print statement prints out 1 or 2
            print(this.v.get())
            messagebox.showerror("Packing Error", "Pack algorithm not selected!")
        else:
          ...(this code not relevant)

【问题讨论】:

  • 请添加使用的 GUI 工具包并定义“不工作”您可能需要支付更多费用才能让他们工作......
  • 发生的事情是 elif 语句在不应该运行的时候运行。当我打印“v”的值时,它是 1 或 2,但 elif 语句仍然运行。我正在使用 tkinter,我将进行编辑以指定
  • 应该更新,让我仔细检查一下。
  • 注意:在Python中,if等不是必需的括号条件,实际上是强烈不鼓励这样做的。请注意,在for 中它实际上是不可能的。不要尝试让 Python 代码看起来像“C-ish”!
  • "if 语句正在运行" ...我假设您的意思是条件为真?只需打印值。请注意,只有一个 if 语句。那么,哪个条件是真的呢?

标签: python user-interface tkinter radio-button


【解决方案1】:

elif 总是会触发,因为一个变量不能同时是!= 1 !=2

那不是“语义错误”,而是程序员的逻辑错误。

【讨论】:

    【解决方案2】:

    当您说“如果 x 不是 1 时执行此操作,或者如果 x 不是 2 执行此操作”,它将始终运行。考虑以下值:

    • 0(零):不是1,所以elif测试通过
    • 1(一):是一但不是2,所以elif测试通过
    • 2(二):不是1,所以elif测试通过
    • 3(三):不是1,所以elif测试通过

    【讨论】:

      猜你喜欢
      • 2013-03-18
      • 2021-08-02
      • 2014-08-23
      • 2011-03-02
      • 1970-01-01
      • 2018-07-05
      • 2017-02-17
      • 2021-01-10
      相关资源
      最近更新 更多