【问题标题】:How do I prevent 2 of my radio buttons from lighting up at the same time?如何防止我的 2 个单选按钮同时亮起?
【发布时间】:2023-01-28 11:24:01
【问题描述】:

我正在尝试使用 Tkinter 制作我自己的小石头剪刀布程序,因为我很无聊。我使用单选按钮来指定玩家的动作。但是,出于某种原因,在运行该程序时,3 个单选按钮中的 2 个会亮起。偶尔 3 个中的 3 个。我认为它不应该这样做。

如有必要,这是我的代码:

from tkinter import *
app=Tk()

playersel=0
RBttn = Radiobutton(text = "Rock", variable = playersel,value = 'Rock')
RBttn2 = Radiobutton(text = "Paper", variable = playersel, value = 'Paper')
RBttn3=Radiobutton(text='Scissors',variable=playersel,value='Scissors')

RBttn.place(x=10,y=10)
RBttn2.place(x=10,y=30)
RBttn3.place(x=10,y=50)

app.mainloop()

如果重要的话,我正在使用 python 3.10.4。

【问题讨论】:

  • playersel 需要是 StringVar() 的实例,其初始值不等于三个单选按钮的三个值,并且也不能为空字符串。例如,playersel = StringVar(value='none')。

标签: python tkinter


【解决方案1】:

如何防止我的 2 个单选按钮同时亮起 时间

  • 为所有 3 个 raidobutton 添加了 IntVar()。
  • 为所有 3 个 raidobutton 添加参数 variable=var。

代码:

from tkinter import *

app = Tk()

var = IntVar()
playersel = 0

RBttn = Radiobutton(app, text="Rock", variable=var, value = 'Rock')
RBttn2 = Radiobutton(app, text="Paper", variable=var, value = 'Paper')
RBttn3 = Radiobutton(app, text='Scissors',variable=var, value='Scissors')

RBttn.place(x=10,y=10)
RBttn2.place(x=10,y=30)
RBttn3.place(x=10,y=50)

app.mainloop()

前后截图:

【讨论】:

    猜你喜欢
    • 2015-12-23
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 2021-05-11
    相关资源
    最近更新 更多