How do I get the value from radiobuttons? - python

So I'm trying to make a program in python tkinter that creates 3 radiobuttons for different difficulties for the user to choose. I created a variable diffLevel = IntVar() and I'm trying to change it using those radiobuttons. Then, when the user has chosen the difficulty, he presses a button that activates a command that tries to read the value of diffLevel and does different commands depending on its value. But, for some reason, it doesn't work. Here is the code:
win = Tk()
win.geometry('250x250+650+250')
diffLevel = IntVar()
diffChoiceE = Radiobutton(win, text="Easy", variable=diffLevel, value=0)
diffChoiceE.place(x=10, y=10)
diffChoiceM = Radiobutton(win, text="Medium", variable=diffLevel, value=1)
diffChoiceM.place(x=10, y=35)
diffChoiceH = Radiobutton(win, text="Hard", variable=diffLevel, value=2)
diffChoiceH.place(x=10, y=60)
def diffSet():
a = diffLevel.get()
if a == 0:
setSpades()
elif a == 1:
setSpades()
setHearts()
elif a == 2:
setSpades()
setHearts()
setClubs()
setDiamonds()
win.destroy()
ch = Button(win, text="Choose", width=7, height=1, command=diffSet)
ch.place(x=100, y=80)
win.mainloop()
I tried printing 'a', but for some reason, it says '0', even though I selected the radiobutton that makes diffLevel equal 1 or 2. I tried using the ttk module, but then the radiobuttons don't work and all act as if they were pressed. So how can I get the correct value from diffLevel?

I have changed the code a little bit to run on my computer but it seems that the code is working appropriately for me.
win = Tk()
win.geometry('250x250+650+250')
diffLevel = IntVar()
diffChoiceE = Radiobutton(win, text="Easy", variable=diffLevel, value=0)
diffChoiceE.place(x=10, y=10)
diffChoiceM = Radiobutton(win, text="Medium", variable=diffLevel, value=1)
diffChoiceM.place(x=10, y=35)
diffChoiceH = Radiobutton(win, text="Hard", variable=diffLevel, value=2)
diffChoiceH.place(x=10, y=60)
def diffSet():
a = diffLevel.get()
print('Values of a: ',a)
if a == 0:
print('Spades')
elif a == 1:
print('Spades&Hearts')
elif a == 2:
print('Spades&Hearts&Clubs&Diamonds')
#win.destroy()
ch = Button(win, text="Choose", width=7, height=1, command=diffSet)
ch.place(x=100, y=80)
win.mainloop()
I have selected each radio button and they are all working currently printing:
Values of a: 0
Spades
Values of a: 1
Spades&Hearts
Values of a: 2
Spades&Hearts&Clubs&Diamonds
I am using python 3.7 and TkVersion 8.6. Which version are you using ?

Related

I want to press my button in Tkinter GUI to get iput and then get a random word from my list instead of manually typing in my input

import tkinter as tk
Hoogte = 900
breedte = 1440
def doelwitpress(argumenten):
if argumenten == 1:
input("1")
if argumenten == 2:
input("2")
if argumenten == 3:
input("3")
import random
print('Kies uit 1 (kleinst), 2 (kleiner) of 3 (grootsts):')
willekeurigwoord = input()
kleinstedoelwit = ['beneficial', 'eloquent', 'in proximity']
x = random.choice(kleinstedoelwit)
if (willekeurigwoord == 1):
print(x)
kleineredoelwit = ['useful', 'advise', 'commence']
y = random.choice(kleineredoelwit)
if (willekeurigwoord == "2"):
print(y)
grootstedoelwit = ['vehicle', 'combined', 'uproar']
z = random.choice(grootstedoelwit)
if (willekeurigwoord == "3"):
print(z)
root = tk.Tk()
GrafischeUIcanvas = tk.Canvas(root, height=Hoogte)
GrafischeUIcanvas = tk.Canvas(root, width=breedte)
GrafischeUIcanvas.pack()
achtergrondkleur = tk.Frame(root, bg='#6BAB55')
achtergrondkleur.place(relwidt=1, relheight=1)
kleinstedoelwit = tk.Button(root, text="kleinste doelwit", command=lambda: doelwitpress(1))
kleineredoelwit = tk.Button(root, text="kleinere doelwit", command=lambda: doelwitpress(2))
grootstedoelwit = tk.Button(root, text="grootste doelwit", command=lambda: doelwitpress(3))
kleinstedoelwit.pack(side="left")
kleineredoelwit.pack(side="bottom")
grootstedoelwit.pack(side="right")
root.mainloop()
when i only run my code without gui i can get a word out but i have to manually type it in. I want my tkinter button to be my input and get an output from my code. I basically want to press a button in the UI, the UI then inputs a number and that number equals to one of the lists whith random words. The only thing that happens right now is that it shows the input of my press and then it crashes after 1 input. It doesnt even display 1 random chosen word.
Im using tkinter and random.choice
You should be using Entry widget to get the input from the user and Label or a messagebox to display output.
I have rewritten your code, without changing any logic. (Note: This is only for demonstration purposes as I have no idea how your GUI should come together. It's up to you to make further changes)
In the below code, I have set entry and entry2 to a variable var and var1 respectively. You can use this variable to get and set the value in the Entry widget as shown in the below code.
For output, I have used a label. You may change the text by using label.config(text='abc') or label.configure(text='abc') or just by accessing the text like lable[text] = 'abc'
import tkinter as tk
import random
Hoogte = 900
breedte = 1440
def doelwitpress(argumenten):
if argumenten == 1:
var.set('1')
if argumenten == 2:
var.set('2')
if argumenten == 3:
var.set('3')
lbl['text'] = 'Kies uit 1 (kleinst), 2 (kleiner) of 3 (grootsts):'
#print('Kies uit 1 (kleinst), 2 (kleiner) of 3 (grootsts):')
#willekeurigwoord = input()
kleinstedoelwit = ['beneficial', 'eloquent', 'in proximity']
x = random.choice(kleinstedoelwit)
if (var2.get() == '1'):
lbl['text'] = x
#print(x)
kleineredoelwit = ['useful', 'advise', 'commence']
y = random.choice(kleineredoelwit)
if (var2.get() == "2"):
lbl['text'] = y
#print(y)
grootstedoelwit = ['vehicle', 'combined', 'uproar']
z = random.choice(grootstedoelwit)
if (var2.get() == "3"):
lbl['text'] = z
#print(z)
root = tk.Tk()
var = tk.StringVar()
var2 = tk.StringVar()
GrafischeUIcanvas = tk.Canvas(root, height=Hoogte)
GrafischeUIcanvas = tk.Canvas(root, width=breedte)
GrafischeUIcanvas.pack()
achtergrondkleur = tk.Frame(root, bg='#6BAB55')
achtergrondkleur.place(relwidt=1, relheight=1)
#achtergrondkleur.pack()
kleinstedoelwit = tk.Button(root, text="kleinste doelwit", command=lambda: doelwitpress(1))
kleineredoelwit = tk.Button(root, text="kleinere doelwit", command=lambda: doelwitpress(2))
grootstedoelwit = tk.Button(root, text="grootste doelwit", command=lambda: doelwitpress(3))
kleinstedoelwit.pack(side="left")
kleineredoelwit.pack(side="bottom")
grootstedoelwit.pack(side="right")
lbl = tk.Label(root, bg='#6BAB55', fg='red')
lbl.pack()
entry = tk.Entry(root, textvariable=var)
entry.pack()
entry2 = tk.Entry(root, textvariable=var2)
entry2.pack()
root.mainloop()

How to select only one Radiobutton in tkinter

I have two radiobutton in my GUI but i want to able select only one at a time with the code below am able to select both radiobutton . I tried the checkbutton which also i can select both options.
from tkinter import *
def content():
if not option1.get() and not option2.get():
print("not allowed, select one dude")
else:
print("welcome dude")
option1.set(False)
option2.set(False)
root = Tk()
root.geometry("400x400")
option1 = BooleanVar(value=False)
R1 = Radiobutton(root, text="MALE", value=1, var=option1)
R1.pack()
option2 = BooleanVar(value=False)
R2 = Radiobutton(root, text="FEMALE", value=2, var=option2)
R2.pack()
b = Button(root, text="print", command=content)
b.pack(side="bottom")
root.mainloop()
You must bind both radiobuttons to the same variable.
Besides, the variable will receive the value specified in the value keyword argument.
I suggest you do the following:
option = StringVar()
R1 = Radiobutton(root, text="MALE", value="male", var=option)
R2 = Radiobutton(root, text="FEMALE", value="female", var=option)
You can know what item is currently selected, by tracing the option variable, and by calling its get method.
For instance, the following will print either "male" or "female" whenever the corresponding radiobutton is checked.
def print_var(*_):
print(option.get())
root = Tk()
root.geometry("400x400")
option = StringVar()
R1 = Radiobutton(root, text="MALE", value="male", var=option)
R2 = Radiobutton(root, text="FEMALE", value="female", var=option)
R1.pack()
R2.pack()
option.trace('w', print_var)
root.mainloop()
A more complete example, according to your demand.
This script will display a window with two radiobuttons and a button.
When the button is clicked, a message is printed that depends upon whether an option was selected or not.
from tkinter import *
def validate():
value = option.get()
if value == "male":
print("Welcome dude")
elif value == "female":
print("Welcome gurl")
else:
print("An option must be selected")
root = Tk()
root.geometry("400x400")
option = StringVar()
R1 = Radiobutton(root, text="MALE", value="male", var=option)
R2 = Radiobutton(root, text="FEMALE", value="female", var=option)
button = Button(root, text="OK", command=validate)
R1.pack()
R2.pack()
button.pack()
root.mainloop()
As a side note, you should never import a module with a star, eg from tkinter import *.
In short, it pollutes the namespace. More on this post.
I presume you are wanting to create one radio button with multiple values which only allows one selection? You would be better to populate an array and run a loop to fill the radio button. Perhaps something like this?
from tkinter import *
root = Tk()
root.geometry("400x400")
GENDERS = [
("Male", "M"),
("Female", "F"),
("Other", "O")
]
v = StringVar()
v.set("L") # initialize
for text, gender in GENDERS:
b = Radiobutton(root, text=text,
variable=v, value=gender)
b.pack(anchor=W)
root.mainloop()
The easiest way to do it that i found is this -
you have to give them both the same variable so that compiler can know that the user can only choose one...
from tkinter import *
window = Tk()
window.geometry("100x100")
var = IntVar()
radio = Radiobutton(window, text="this", variable=var, value=1)
radio.pack()
radio2 = Radiobutton(window, text="or this", variable=var, value=2)
radio2.pack()
window.mainloop()

Tkinter questionnaire based on get() method

I am trying to make my first GUI script based on the answers of 2 questions. I'll show an example of the non GUI script
while True:
ammount = input("What is your debt")
if ammount.isdigit() == True:
break
else:
print("Please try typing in a number")
while True:
month = input("In which month did the debt originate?")
if month not in ["January", "February"]:
print("Try again")
else:
break
The point of this script is that it is scalable with all the questions one may add, I want to understand it in the same way in Tkinter. I'll show what I've tried:
from tkinter import *
def click():
while True:
entered_text = text_entry.get()
if entered_text .isdigit() == False:
error = Label(window, text="Try again", bg = "black", fg="red", font="none 11").grid(row = 3, column = 2, sticky= W).pack()
else:
break
return True
window = Tk()
window.title("Tax calculator")
window.configure(background="black")
monto = Label(window, text="¿What is your debt?", bg="black", fg="white", font="none 12 bold")
monto.grid(row = 1, column = 0, sticky= W)
text_entry = Entry(window, width = 20, bg="white")
text_entry.grid(row = 2, column=2, sticky=W)
output = Button(window, text = "Enter", width = 6, command = click)
output.grid(row = 3, column = 0, sticky = W)
The thing is, I can't add a Label() method in the if/else of the click() method, because I would like to ask a new question once the condition is met. I can't also can't get True from click once the condition is met, because the input comes from Button() method. Thanks in advance
You don't actually need any loops here, a simple if statement would be enough to do the trick. Also, there is no need to recreate the label every time, you can just configure() its text. And, note that indexing starts from 0 - so, in your grid, actual first row (and column) needs to be numbered 0, not 1. Besides that, I suggest you get rid of import *, since you don't know what names that imports. It can replace names you imported earlier, and it makes it very difficult to see where names in your program are supposed to come from. You might want to read what PEP8 says about spaces around keyword arguments, as well:
import tkinter as tk
def click():
entered_text = text_entry.get()
if not entered_text.isdigit():
status_label.configure(text='Please try again')
text_entry.delete(0, tk.END)
else:
status_label.configure(text='Your tax is ' + entered_text)
text_entry.delete(0, tk.END)
root = tk.Tk()
root.title('Tax calculator')
root.configure(background='black')
monto = tk.Label(root, text='¿What is your debt?', bg='black', fg='white', font='none 12 bold')
monto.grid(row=0, column=0, padx=10, pady=(10,0))
text_entry = tk.Entry(root, width=20, bg='white')
text_entry.grid(row=1, column=0, pady=(10,0))
status_label = tk.Label(root, text='', bg='black', fg='red', font='none 11')
status_label.grid(row=2, column=0)
button = tk.Button(root, text='Enter', width=17, command=click)
button.grid(row=3, column=0, pady=(0,7))
root.mainloop()
I forgot to mention, if your application gets bigger, you might be better off using a class.

Python tkinter binding a function to a button

from tkinter import *
root = Tk()
root.title("Tip & Bill Calculator")
totaltxt = Label(root, text="Total", font=("Helvitca", 16))
tiptxt = Label(root, text="Tip (%)", font=("Helvitca", 16))
peopletxt = Label(root, text="people", font=("Helvitca", 16))
totaltxt.grid(row=0, sticky=E)
tiptxt.grid(row=1, sticky=E)
peopletxt.grid(row=2, sticky=E)
totalentry = Entry(root)
tipentry = Entry(root)
peopleentry = Entry(root)
totalentry.grid(row=0, column=2)
tipentry.grid(row=1, column=2)
peopleentry.grid(row=2, column=2)
ans = Label(root, text = "ANS")
ans.grid(row=4)
def answer(event):
data1 = totalentry.get()
data2 = tipentry.get()
data3 = peopleentry.get()
if tipentry.get() == 0:
ans.configure(str((data1/data3)), text="per person")
return
elif data1 == 0:
ans.configure(text="Specify the total")
return
elif data3 == 0 or data3 ==1:
ans.configure(str(data1*(data2/100+1)))
return
elif data1 == 0 and data2 == 0 and data3 ==0:
ans.configure(text = "Specify the values")
return
else:
ans.configure(str((data1*(data2/100+1)/data3)), text="per person")
return
bf = Frame(root)
bf.grid(row=3, columnspan=3)
calc = Button(bf, text ="Calculate", fg = "black", command = answer)
calc.bind("<Button-1>", answer)
calc.grid(row=3, column=2)
root.mainloop()
I'm trying to make a tip and bill calculator with a simple design just to learn and experiment. However, I encountered a horrible problem that kept haunting for days, I usually struggle with functions in python and I'm trying to bind a function to a calculate button, which I managed to make it appear. However, I can't manage to get it to work. After some messing around I ended with this error, when I click the calculate button.
This is the error after I click the calculate button:
TypeError: answer() missing 1 required positional argument: 'event'
Commands bound to a button do not get an argument, as the nature of the event is already known. Delete 'event'.
You also bind the answer function to an event. The result is that answer is called both without and with an event argument. Get rid of the bind call.
Follow hint given by Bryan. Stop passing a digit string to .configure as a positional parameter. tk will try to interpret is as dictionary. Instead, add the number string to the rest of the label string.
Like rows, columns start from 0.
The frame is not needed.
The following revision works.
from tkinter import *
root = Tk()
root.title("Tip & Bill Calculator")
totaltxt = Label(root, text="Total", font=("Helvitca", 16))
tiptxt = Label(root, text="Tip (%)", font=("Helvitca", 16))
peopletxt = Label(root, text="people", font=("Helvitca", 16))
totaltxt.grid(row=0, column=0, sticky=E)
tiptxt.grid(row=1, column=0, sticky=E)
peopletxt.grid(row=2, column=0, sticky=E)
totalentry = Entry(root)
tipentry = Entry(root)
peopleentry = Entry(root)
totalentry.grid(row=0, column=1)
tipentry.grid(row=1, column=1)
peopleentry.grid(row=2, column=1)
ans = Label(root, text = "ANS")
ans.grid(row=4, column=0, columnspan=2, sticky=W)
def answer():
total = totalentry.get()
tip = tipentry.get()
people = peopleentry.get()
if not (total and tip):
ans['text'] = 'Enter total and tip as non-0 numbers'
else:
total = float(total)
tip = float(tip) / 100
people = int(people) if people else 1
ans['text'] = str(round(total * tip / people, 2)) + " per person"
calc = Button(root, text ="Calculate", fg = "black", command = answer)
calc.grid(row=3, column=1)
root.mainloop()

Need assistance Tkinter in Python 2.7

I am writing a subnetting program in Python and I have come across a problem.
So far everything is working minus one thing. I dont know how to change a label in a method. in the code below, SubnetM is the variable being used to show the subnet mask. It is set to 0 by default but when you select HOSTS and enter 6 as Quantity. The 0 does not change to 255.255.255.248. PLEASE HELP
from Tkinter import *
SubnetM = 0
def beenclicked():
radioValue = relStatus.get()
return
def changeLabel():
if radio1 == 'HOSTS':
if Quantity == 6:
SubnetM = "255.255.255.248"
return
app = Tk()
app.title("SUBNET MASK CALCULATOR")
app.geometry('400x450+200+200')
labelText = StringVar()
labelText.set("WELCOME!")
label1 = Label(app,textvariable=labelText, height=4)
label1.pack()
relStatus = StringVar()
relStatus.set(None)
radio1 = Radiobutton(app, text="HOSTS", value="HOSTS", variable=relStatus, command=beenclicked).pack()
radio1 = Radiobutton(app, text="NETWORKS", value="NETWORKS", variable=relStatus, command=beenclicked).pack()
label2Text = StringVar()
label2Text.set("~Quantity~")
label2 = Label(app, textvariable=label2Text, height=4)
label2.pack()
custname = IntVar(None)
Quantity = Entry(app,textvariable=custname)
Quantity.pack()
label3Text = StringVar()
label3Text.set("Your Subnet Mask is...")
label3 = Label(app, textvariable=label3Text, height=4)
label3.pack()
label4Text = StringVar()
label4Text.set(SubnetM)
label4 = Label(app, textvariable=label4Text, height=4)
label4.pack()
button1 = Button(app, text="GO!", width=20, command=changeLabel)
button1.pack(padx=15, pady=15)
app.mainloop()
To fix your problem, make changeLabel like this:
def changeLabel():
# Get the radiobutton's StringVar and see if it equals "HOSTS"
if relStatus.get() == 'HOSTS':
# Get the entrybox's IntVar and see if it equals 6
if custname.get() == 6:
# Set the label's StringVar to "255.255.255.248"
label4Text.set("255.255.255.248")
Also, the .pack method of a Tkinter widget returns None. So, you should make the part that defines the radiobuttons like this:
radio1 = Radiobutton(app, text="HOSTS", value="HOSTS", variable=relStatus, command=beenclicked)
radio1.pack()
radio2 = Radiobutton(app, text="NETWORKS", value="NETWORKS", variable=relStatus, command=beenclicked)
radio2.pack()

Categories