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()
Related
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 ?
I am trying to print a corresponding value to the index of a list from another list like so:
print(safeDis[chem.index(self.drop2)])
but when doing this i get the above error. I believe i had this working in a previous iteration but i cannot find the one that was.
import tkinter as tk
from tkinter import ttk
safeDis = [4,88,18,50,12,100]
chem = ["HTP 50%","HTP 84%","HTP 90%","Kerosene","Benzene"]
class Page4:
def __init__(self,root):
self.root = root
self.toplbl = ttk.Label(root, text="Select firing point meterials ",font=("arial",12)) #lable for select meterial 1
self.lbl1 = ttk.Label(root, text="Meterial 1: ",font=("arial",10)) #lable for select meterial 1
self.lbl2 = ttk.Label(root, text = "Meterial 2: " ,font = ("arial",10)) #lable for meterial 2
self.masslbl = ttk.Label(root, text="Mass in Kg:",font=("arial",10))
self.masslbl2 = ttk.Label(root, text="Mass in Kg:",font=("arial",10))
self.typelbl = ttk.Label(root, text="Type:",font=("arial",10))
self.typelbl2 = ttk.Label(root, text="Type:",font=("arial",10))
self.Apply = ttk.Button(root, text="Apply", command = self.new_window) #button to confirm the meterial choices
self.Back = ttk.Button(root, text="Back", command = print("DONG"))
self.mass1 = ttk.Entry(root, width=8)
self.mass2 = tk.Entry(root,width=8)
self.clicked = tk.StringVar() #set the variable to a string value allowing the meterial names to apeer in it
self.clicked.set(chem[3]) #set the default meterial from the chem list
self.clicked2 = tk.StringVar()
self.clicked2.set(chem[3])
self.drop2 = tk.OptionMenu(root, self.clicked2, *chem) #setup the dropdown menue with optionmenue function set to the chem list
self.drop = tk.OptionMenu(root, self.clicked, *chem)
self.toplbl.grid(column=0, row=0,columnspan=3,sticky="w",padx=10,pady=10) #place meterial label 1
self.lbl1.grid(column=0, row=1,padx=10) #place meterial label 1
self.lbl2.grid(column=0, row=3,padx=10) #place meterial label 2
self.mass1.grid(column=2, row=2)
self.mass2.grid(column=2, row=4)
self.masslbl.grid(column=1, row=2)
self.masslbl2.grid(column=1, row=4)
self.typelbl.grid(column=1, row=1,sticky="w")
self.typelbl2.grid(column=1, row=3,sticky="w")
self.drop.grid(column=2, row=1) #place the dropdown menue
self.drop2.grid(column=2, row=3)
self.Apply.grid(column=2,row=5,pady=10,padx=10)
self.Back.grid(column=1,row=5,pady=10,padx=10)
print(safeDis[chem.index(self.drop2)])
def new_window(self):
#print(dongalong)
for widget in self.root.winfo_children():
widget.destroy()
self.app = Page3(self.root)
#class Page5:
def main():
root = tk.Tk()
app = Page4(root)
root.mainloop()
if __name__ == '__main__':
main()
The problem was that self.drop2 is an object of OptionMenu, not the value of it. To get the value returned by it, use the get() method on its variable defined (self.clicked2.get())
So it should be:
print(safeDis[chem.index(self.clicked2.get())])
Hope it solved the error, do let me know if any more doubts
Cheers
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()
When I type in entrybox1 it automatically appears in entrybox2. So is like anything that happens entrybox1 happens to entrybox2.
Below is my code
from Tkinter import*
import random
class Love:
def __init__(self):
window = Tk()
window.title("Love Calculator")
window.geometry("300x180")
frame1 = Frame(window)
frame1.pack()
self.lbl = Label(frame1, text = "Love is Pure",fg="white",bg = "blue")
self.lbl2=Label(frame1, text ="are you meant for one another",fg="White",bg = "red")
self.lbl3=Label(frame1,text="Let FIND OUT!!",fg="white",bg = "green")
self.lbl.pack()
self.lbl2.pack()
self.lbl3.pack()
frame2=Frame(window)
frame2.pack()
label = Label(frame2,text = "Your Name")
label2 = Label(frame2, text= "Your Lovers name")
self.msg = StringVar
entry1 = Entry(frame2, textvariable =self.msg)
self.out = StringVar
entry2 = Entry(frame2, textvariable =self.out)
btCalculate=Button(frame2, text="Calculate", command=self.processButton)
label.grid(row=1,column=1)
label2.grid(row=2,column=1)
entry1.grid(row=1,column=2)
entry2.grid(row=2,column=2)
btCalculate.grid(row=4,column=3,sticky=E)
Both of your Entry widgets are effectively using the same textvariable. This is because you are using StringVar wrong. You aren't creating newStringVars, you're merely referencing the class.
In short, you need to do this:
self.msg = StringVar()
... Rather than this:
self.msg = StringVar
Notice the use of ().
I would like to ask how would I go about maybe creating a 'LIVE' text box in python? This program is a simulator for a vending machine (code below). I want there to be a text box showing a live credit update How do you do that in tkinter?
For Example: Say there is a box for credit with 0 inside it in the middle of the window. When the 10p button is pressed the box for credit should change from '0' to '0.10'.
Is it possible to do thit in tkinter and python 3.3.2?
Thank you in advance!
import sys
import tkinter as tk
credit = 0
choice = 0
credit1 = 0
coins = 0
prices = [200,150,160,50,90]
item = 0
i = 0
temp=0
n=0
choice1 = 0
choice2 = 0
credit1 = 0
coins = 0
prices = [200,150,160,50,90]
item = 0
i = 0
temp=0
n=0
choice1 = 0
choice2 = 0
def addTENp():
global credit
credit+=0.10
def addTWENTYp():
global credit
credit+=0.20
def addFIFTYp():
global credit
credit+=0.50
def addPOUND():
global credit
credit+=1.00
def insert():
insert = Tk()
insert.geometry("480x360")
iLabel = Label(insert, text="Enter coins.[Press Buttons]").grid(row=1, column=1)
tenbutton = Button(insert, text="10p", command = addTENp).grid(row=2, column=1)
twentybutton = Button(insert, text="20p", command = addTWENTYp).grid(row=3, column=1)
fiftybutton = Button(insert, text="50p", command = addFIFTYp).grid(row=4, column=1)
poundbutton = Button(insert, text="£1", command = addPOUND).grid(row=5, column=1)
insert()
Sure you can! Just add another label to the frame, and update the text attribute whenever one of your add functions is called. Also, you can simplify that code, using one add function for all the different amounts.
def main():
frame = Tk()
frame.geometry("480x360")
Label(frame, text="Enter coins.[Press Buttons]").grid(row=1, column=1)
display = Label(frame, text="") # we need this Label as a variable!
display.grid(row=2, column=1)
def add(amount):
global credit
credit += amount
display.configure(text="%.2f" % credit)
Button(frame, text="10p", command=lambda: add(.1)).grid(row=3, column=1)
Button(frame, text="20p", command=lambda: add(.2)).grid(row=4, column=1)
Button(frame, text="50p", command=lambda: add(.5)).grid(row=5, column=1)
Button(frame, text="P1", command=lambda: add(1.)).grid(row=6, column=1)
frame.mainloop()
main()
Some more points:
note that you define many of your variables twice
you should not give a variable the same name as a function, as this will shadow the function
probably just a copy paste error, but you forgot to call mainloop and your tkinter import is inconsistent with the way you use the classes (without tk prefix)
you can do the layout right after creating the GUI elements, but note that in this case not the GUI element will be bound to the variable, but the result of the layouting function, which is None
Borrowing a framework from tobias_k's excellent answer, I would recommend you use a DoubleVar instead.
from tkinter import ttk
import tkinter as tk
def main():
frame = Tk()
frame.geometry("480x360")
credit = tk.DoubleVar(frame, value=0)
# credit = tk.StringVar(frame, value="0")
ttk.Label(frame, textvariable = credit).pack()
def add_credit(amt):
global credit
credit.set(credit.get() + amt)
# new_credit = str(int(credit.get().replace(".",""))+amt)
# credit.set(new_credit[:-2]+"."+new_credit[-2:])
ttk.Button(frame, text="10p", command = lambda: add_credit(0.1)).pack()
# ttk.Button(frame, text="10p", command = lambda: add_credit(10)).pack()
ttk.Button(frame, text="20p", command = lambda: add_credit(0.2)).pack()
# ttk.Button(frame, text="20p", command = lambda: add_credit(20)).pack()
ttk.Button(frame, text="50p", command = lambda: add_credit(0.5)).pack()
# ttk.Button(frame, text="50p", command = lambda: add_credit(50)).pack()
ttk.Button(frame, text="P1", command = lambda: add_credit(1.0)).pack()
# ttk.Button(frame, text="P1", command = lambda: add_credit(100)).pack()
frame.mainloop()
The comments in that code is an alternate implementation that will work better, if only just. This will guarantee you won't have any strange floating-point errors in your code.