我有这个代码,要求用户选择其中一个选项。我用了radiobuttons。在用户选择他的选择之后,选择将使用另一个if语句。我已经将选项的变量指定为variable = specialistchoose
。但是当我使用specialistchoose
或specialistchoose.get()
时,它不起作用。有人可以帮忙吗?
specialistchoose = IntVar()
r1 = Radiobutton (f2, text = "Cardiology", variable = specialistchoose, value = 1, command = command_r1 )
r1.grid(row = 4, column = 0, stick = W)
r2 = Radiobutton (f2, text = "Gastroenterology", variable = specialistchoose, value = 2, command = command_r2)
r2.grid(row = 4, column = 1,stick = W )
r3 = Radiobutton (f2, text = "Dermatology", variable = specialistchoose, value = 3, command = command_r3)
r3.grid (row = 4, column = 2,stick = W )
r4 = Radiobutton (f2, text = "Psychiatry", variable = specialistchoose, value = 4, command = command_r4)
r4.grid (row = 5, column = 0,stick = W )
r5 = Radiobutton (f2, text = "Dentist", variable = specialistchoose, value = 5, command = command_r5)
r5.grid(row = 5, column = 1,stick = W )
f2.place(relx = 0.01, rely = 0.125, anchor = NW)
Label(f1, text = "Specialist").place(relx = .06, rely = 0.125, anchor = W)
f1.grid(stick = W)
if specialistchoose.get() == "Cardiology":
file = open ("test2.txt", "w")
file.write ("Specialist : Cardiology")
file.close()
elif specialistchoose.get() == "Gastroenterology":
file = open ("test2.txt", "w")
file.write ("Specialist : Gastroenterology")
file.close()
elif specialistchoose.get() == "Dermatology":
file = open ("test2.txt", "w")
file.write ("Specialist : Dermatology")
file.close()
elif specialistchoose.get() == "Psychiatry":
file = open ("test2.txt", "w")
file.write("Specialist : Psychiatry")
file.close()
elif specialistchoose.get() == "Dentist":
file = open ("test2.txt", "w")
file.write("Specialist : Dentist")
file.close()
注意:这只是较长代码的示例。
答案 0 :(得分:2)
由于您只是在创建后才get()
了它们的值,因此您只能得到它们的初始值,仅此而已。
尝试使用command
或其他按钮获取其值。
不知道你在command_rX
下有什么,但你应该将它们分开,并放在相应的command
下。
此外,由于您的变量为IntVar()
,因此您指定的变量为value
,因此您将获得{1}}。
def command_r1():
with open('test2.txt', 'w') as file:
file.write ("Specialist : Cardiology")
def command_r2():
with open('test2.txt', 'w') as file:
file.write ("Specialist : Gastroenterology")
#etc...
或创建一个按钮,当它点击它时,我会获得价值,然后做所有其他的事情。
def external_button_callback():
radioValue = specialistchoose.get()
if radioValue == 1:
with open('test2.txt', 'w') as file:
file.write ("Specialist : Cardiology")
#etc...
btn = Button(f2, text= "Get Value" command = external_button_callback)
btn.grid(row=6, column=0)
另一个小问题是,在使用文件时,最好使用with
语句,因为当您移出范围时它会自动处理关闭,并且您不必担心每次都关闭。
每次更改值时,自从您在w
模式下打开txt文件后,该文件将从头开始创建。我不知道这是不是你想要的,但想要提醒一下。
答案 1 :(得分:0)
radiobutton
变量的值与其text
无关。您将变量specialistchoose
声明为IntVar
,因此它将是一些int。
if specialistchoose.get() == "Cardiology":
永远不会是True
昨天我在这里就同一主题回答了你的问题:Gray out a frame after clicking a radiobutton Tkinter
如果您将func
更改为以下内容:
def func():
print specialistchoose.get()
您将能够看到每个radiobutton
在按下时获得的值。
如果他们被按下,你可以在那里制造一个条件。