I am working on a script with tkinter, but something weird is happening.
I have two radioButtons:
way=False
RadioButton0=Radiobutton(root,text="From",variable=way,value=False)
RadioButton1=Radiobutton(root,text="To",variable=way,value=True)
RadioButton0.grid(column=0,row=2)
RadioButton1.grid(column=1,row=2)
And a text entry field:
entryValue=0
entryField=Entry(root,textvariable=entryValue)
entryField.grid(column=0,row=4)
When I enter 0 in entry field, RadioButton0 is automatically selected, when I enter 1, RadioButton1 is selected and for any other value, they both get selected...
This works vice versa: when I select RadioButton0, entry field changes to 0 and when I select RadioButton1, entry field changes to 1... Also, entryValue is later seen as 0. Variable way should only be modified by radio buttons...
Why is that happening? Am I doing something I shouldn't? And how do I fix it?
variable and textvariable should be both different variable objects, not just built-in data types:
way=BooleanVar(root)
way.set(False)
# ...
entryValue=StringVar(root)
entryValue.set("0")
you can use a command to call a method and set the value. Please refer attached code.
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
frame = Frame(root)
frame.pack()
labelframe = LabelFrame(frame, text="This is a LabelFrame")
labelframe.pack(fill="both", expand="yes")
var = IntVar()
R1 = Radiobutton(labelframe, text="Option 1", variable=var, value=1,
command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(labelframe, text="Option 2", variable=var, value=2,
command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(labelframe, text="Option 3", variable=var, value=3,
command=sel)
R3.pack( anchor = W)
label = Label(labelframe)
label.pack()
Related
I have 2 Entrys and one button. I want to make that button's state disabled until the two Entrys are filled in. How can I achieve that?
howManyStocksLabel = Label(root, text = "How many stocks do you want to evaluate?")
howManyStocksLabel.grid(row = 1, column = 0)
howManyStocksEntry = Entry(root, borderwidth = 3)
howManyStocksEntry.grid(row = 1, column = 1)
riskLabel = Label(root, text = "Enter risk %")
riskLabel.grid(row = 2, column = 0, sticky = 'w')
riskEntry = Entry(root, borderwidth = 3)
riskEntry.grid(row = 2, column = 1)
nextButton = Button(root, text = "Next!", width = 20, height = 2,state = DISABLED,
fg = 'green', bg = 'white',
command= lambda: myClick(riskEntry, howManyStocksEntry, var))
nextButton.grid(row = 4, column = 1)
I tried to check whether the entries are filled in or not by:
if(riskEntry.get() != ""):
....................
but it just doesn't work.
You need to check if the value is there after the user inputs it. Also, you can use tk.StringVar() as a text variable and trace it.
Here is an example:
import tkinter as tk
def check_entry(*args):
if r1.get() and r2.get():
b1.config(state='normal')
else:
b1.config(state='disabled')
root = tk.Tk()
r1 = tk.StringVar(master=root)
r2 = tk.StringVar(master=root)
e1 = tk.Entry(root, textvariable=r1)
e1.pack()
e2 = tk.Entry(root, textvariable=r2)
e2.pack()
b1 = tk.Button(root, text='Click Me!', state='disabled')
b1.pack()
r1.trace('w', check_entry)
r2.trace('w', check_entry)
root.mainloop()
You will need to use a binding on your entry widgets to check whether the user has entered anything into the entry or not.
This code will fire the check_entry function every time the user types in one of the entry boxes:
riskEntry.bind('<KeyRelease>', check_entry)
howManyStocksEntry.bind('<KeyRelease>', check_entry)
Then your check_entry function might look like this:
def check_entry(event): #event is required for all functions that use a binding
if riskEntry.get() and howManyStocksEntry.get():
nextButton.config(state=NORMAL)
else:
nextButton.config(state=DISABLED)
One way to do it would be to utilize the ability to "validate" their contents that Entry widgets support — see adding validation to an Entry widget — but make it check the contents of multiple Entry widgets and change the state of a Button accordingly.
Below shows how to do this via a helper class that encapsulates most of the messy details needed to make doing it relatively painless. Any number of Entry widgets can be "watched", so it scales well to handle forms consisting of many more than merely two entries.
from functools import partial
import tkinter as tk
from tkinter.constants import *
class ButtonEnabler:
""" Enable/disable a Button depending on whether all specified Entry widgets
are non-empty (i.e. contain at least one character).
"""
def __init__(self, button, *entries):
self.button = button
self.entries = entries
for entry in self.entries:
func = root.register(partial(self.check_entries, entry))
entry.config(validate="key", validatecommand=(func, '%P'))
def check_entries(self, this_entry, new_value):
other_entries = (entry for entry in self.entries if entry is not this_entry)
all_others_filled = all(entry.get() for entry in other_entries)
combined = bool(new_value) and all_others_filled
self.button.config(state=NORMAL if combined else DISABLED)
return True
root = tk.Tk()
howManyStocksLabel = tk.Label(root, text="How many stocks do you want to evaluate?")
howManyStocksLabel.grid(row=1, column=0)
howManyStocksEntry = tk.Entry(root, borderwidth=3)
howManyStocksEntry.grid(row=1, column=1)
riskLabel = tk.Label(root, text="Enter risk %")
riskLabel.grid(row=2, column=0, sticky='w')
riskEntry = tk.Entry(root, borderwidth=3)
riskEntry.grid(row=2, column=1)
nextButton = tk.Button(root, text="Next!", width=20, height=2, state=DISABLED,
fg='green', bg='white', disabledforeground='light grey',
command=lambda: myClick(riskEntry, howManyStocksEntry, var))
nextButton.grid(row=4, column=1)
enabler = ButtonEnabler(nextButton, howManyStocksEntry, riskEntry)
root.mainloop()
I'm trying to get the value of the dropdown list from another Pyton file in the same project.
This is my code in input.py file:
class Input:
Budget = {'Flexible', 'Variable', 'Fixed'}
def __init__(self):
root =Tk()
root.title('Input window V1')
root.geometry('1300x690')
root.resizable(False, False)
frame = Frame(root, width=1000, height=680)
frame.configure(background="gray28")
frame.pack(fill=BOTH, expand=True)
lbl1 = Label(root, bg="gray28", pady=1, text='Budget:', fg="cyan2" , font=("Helvetica", 20))
lbl1.place(x=240, y=225)
var1 = StringVar(root)
#var1.set("None") # default value (Not in use)
pl1 = OptionMenu(root, var1, *self.Budget )
pl1.config(width=20, bg="GREEN", fg="white")
pl1.place(x=470, y=230)
button1 = Button(root, text="GO Hybrid !", command=dashboard)
button1.config(width=25, bg="white")
button1.place(x=600, y=590)
root.mainloop()
and this is the code in the other file I got and I want to get the selected value of pl1 (getting Budget List selected value).
from input import Input
print(Input.Budget)
print (var1.get())
It does give me all "Budget" list but bot the selected value. this is the Error:
NameError: name 'var1' is not defined
Where I should declare it?
Thanks!
If you’re trying to get var1 from another file, initialize your object first.
a = Input()
print(a.var1)
In your __init__:
self.var1 = StringVar(root)
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()
I am trying to make a GUI where as soon as the user inputs an integer into a ttk.entry field, that many checkbuttons need to appear below it. For example, if they put "5" into the entry widget, 5 check buttons need to appear below the entry field.
Edit:
What I ended up using:
self.number_of_stages = tk.IntVar()
self.check_box_dict={}
self.num_of_stages={}
self.stagetempvar={}
self.equipment_widgets={}
def centrifugal_compressor_widgets(self):
self.equipment_widgets.clear()
self.equipment_widgets["NumOfStagesLabelCentComp"]=tk.Label(self.parent, text="Number of Stages:", bg="white")
self.equipment_widgets["NumOfStagesLabelCentComp"].place(relx=0.5, y=260, anchor="center")
self.equipment_widgets["NumOfStagesEntryCentComp"]=ttk.Entry(self.parent, textvariable=self.number_of_stages)
self.equipment_widgets["NumOfStagesEntryCentComp"].place(relx=0.5, y=290, anchor="center")
def OnTraceCentComp(self, varname, elementname, mode):
for key in self.check_box_dict:
self.check_box_dict[key].destroy()
try:
if self.number_of_stages.get() <=15 :
i=1
self.stagetempvar.clear()
while i <= self.number_of_stages.get():
self.stagetempvar[i]=tk.StringVar()
self.stagetempvar[i].set("Closed")
self.check_box_dict[i]=ttk.Checkbutton(self.parent, text=i, offvalue="Closed", onvalue="Open",variable=self.stagetempvar[i])
self.check_box_dict[i].place(relx=(i*(1/(self.number_of_stages.get()+1))), y=360, anchor="center")
i+=1
except:
pass
take a look at the below and let me know what you think...
A very ugly, super basic example:
from Tkinter import *
root = Tk()
root.geometry('200x200')
root.grid_rowconfigure(0, weight = 1)
root.grid_columnconfigure(0, weight = 1)
win1 = Frame(root, bg= 'blue')
win1.grid(row=0, column=0, sticky='news')
number = IntVar()
entry = Entry(win1, textvariable = number)
entry.pack()
confirm = Button(win1, text = 'Press to create widgets...', command = lambda:create_widgets(number.get()))
confirm.pack()
def create_widgets(number):
for n in range(0,number):
Checkbutton(win1, text = 'Checkbutton number : %s' % n).pack()
root.mainloop()
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()