I’m trying to create a form where a user picks a time, and depending on the option they pick. It is then displayed back to the user once they click the submit button. But when i click an option and submit it prints all four options regardless. I also am trying to make it such that once a user clicks one of the options they are unable to click another. Here is my code so far.
JavaScript
x
36
36
1
from tkinter import *
2
master = Tk()
3
4
btn1 = IntVar()
5
btn2 = IntVar()
6
btn3 = IntVar()
7
btn4 = IntVar()
8
9
def variables():
10
w = btn1.get()
11
print(w)
12
x = btn2.get()
13
print(x)
14
y = btn3.get()
15
print(y)
16
z = btn4.get()
17
print(z)
18
19
theLabel = Label(master, text="What time would you like to go?")
20
theLabel.grid(row=0, columnspan=3)
21
22
option1 = Checkbutton(master, text="Now:", variable=btn1).grid(row=2,
23
column=1, sticky=W)
24
option2 = Checkbutton(master, text="15 Mins:", variable=btn2).grid(row=3,
25
column=1, sticky=W)
26
option3 = Checkbutton(master, text="30 Mins:", variable=btn3).grid(row=4,
27
column=1, sticky=W)
28
option4 = Checkbutton(master, text="1 Hour:", variable=btn4).grid(row=5,
29
column=1, sticky=W)
30
31
Button(master, text='Submit', command=variables).grid(row=7, sticky=W, pady=4)
32
Button(master, text='Quit', command=master.destroy).grid(row=8, sticky=W, pady=4)
33
34
35
mainloop()
36
Advertisement
Answer
Try this:
JavaScript
1
34
34
1
from tkinter import *
2
master = Tk()
3
4
btn1 = IntVar()
5
btn1.set(-1)
6
7
def variables():
8
w = btn1.get()
9
if w == -1:
10
print("You didn't choose any of the options")
11
else:
12
print(str(w)+" min")
13
option1.config(state="disabled")
14
option2.config(state="disabled")
15
option3.config(state="disabled")
16
option4.config(state="disabled")
17
18
theLabel = Label(master, text="What time would you like to go?")
19
theLabel.grid(row=0, columnspan=3)
20
21
option1 = Radiobutton(master, text="Now:", variable=btn1, value=0)
22
option1.grid(row=2, column=1, sticky=W)
23
option2 = Radiobutton(master, text="15 Mins:", variable=btn1, value=15)
24
option2.grid(row=3, column=1, sticky=W)
25
option3 = Radiobutton(master, text="30 Mins:", variable=btn1, value=30)
26
option3.grid(row=4, column=1, sticky=W)
27
option4 = Radiobutton(master, text="1 Hour:", variable=btn1, value=60)
28
option4.grid(row=5, column=1, sticky=W)
29
30
submit_button = Button(master, text='Submit', command=variables)
31
submit_button.grid(row=7, sticky=W, pady=4)
32
destroy_button = Button(master, text='Quit', command=master.destroy)
33
destroy_button.grid(row=8, sticky=W, pady=4)
34
It uses Radiobutton
s and notice that all of them have the same variable
(btn1) but different value
. Also I made it so that the buttons get disabled when the user clicks submit.