I am having problems in my Tkinter project. I am trying to create a simple addition calculator that only computes two numbers and. I am having trouble creating the addition function. I want to create a label that displays the variable 'finalans' which is basically the value of the sum of the two digits that the user inputs in the Entry Box Widgets.
def Addition():
top = Toplevel()
top.geometry("500x500")
global finalans
#First Entry
e = Entry(top)
e.pack()
e.focus_set()
#Function for finding answer
def Answer():
firstval = int(e.get())
secondval = int(m.get())
finalans = firstval + secondval
#Final Answer
answer = Label(top, textvariable=finalans)
answer.pack()
h = Label(top, text="First Numeric Value")
h.pack()
#Second Entry
m = Entry(top)
m.pack()
m.focus_set()
z = Label(top, text="Second Numeric Value")
z.pack()
add2 = Button(top, text="Submit", width=10, command=Answer)
add2.pack()
mainloop()
When I try to run the program and display the answer using the Label widget the label does not display anything at all. There isn't even an error code or anything in the console. How do I make the Label Widget display the variable?
First finalans have to be StringVar().
Second use finalans.set(string) to change it.
And you could create answer label only once.
def Addition():
top = Toplevel()
top.geometry("500x500")
global finalans
finalans = StringVar()
#First Entry
e = Entry(top)
e.pack()
e.focus_set()
#Function for finding answer
def Answer():
firstval = int(e.get())
secondval = int(m.get())
finalans.set( str(firstval + secondval) )
h = Label(top, text="First Numeric Value")
h.pack()
#Second Entry
m = Entry(top)
m.pack()
m.focus_set()
z = Label(top, text="Second Numeric Value")
z.pack()
add2 = Button(top, text="Submit", width=10, command=Answer)
add2.pack()
#Final Answer
answer = Label(top, textvariable=finalans)
answer.pack()
mainloop()
Addition()
Related
I have a Python file that when run, opens a window for simple addition practice. It asks the user for their input, and if the total is correct will output "Right!" and "Oops!" for incorrect. Below all of this is a counter that keeps track of the correct number out of the total. However, at the moment, those numbers both remain zero when user enters their input. What kind of changes would need to be made under the ClicktheButton1 function in order to get this program properly functioning? Thanks.
The output would end up looking like "2 out 4 correct" in the window, updating after each new problem is solved.
from tkinter import *
import random as rn
window = Tk()
window.geometry('350x350')
window.title("C200")
x = rn.randint(0,100)
y = rn.randint(0,100)
correct, incorrect = 0,0
myLabel = Label(window, text="{0}+{1}=".format(x,y), font=("Arial Bold", 15))
myLabel.grid(column=0, row=0)
myLable2 = Label(window, text = "",font=("Arial Bold", 15))
myLable2.grid(column=0, row=5)
mylabel3 = Label(window,text = "0 out of 0 correct",font=("Arial Bold", 15))
mylabel3.grid(column=0, row=10)
mytxt = Entry(window, width=12)
mytxt.grid(column=1,row=0)
def ClicktheButton1():
global x
global y
global correct
global incorrect
myguess = int(mytxt.get())
if x + y == myguess:
myLable2.configure(text = "Right!")
correct += 1
else:
myLable2.configure(text = "Oops!")
incorrect += 1
x = rn.randint(0,100)
y = rn.randint(0,100)
mytxt.focus()
mytxt.delete(0,END)
myLabel.configure(text = "{0}+{1}=".format(x,y))
btn1 = Button(window, text="check", command = ClicktheButton1)
btn1.grid(column=0, row=7)
def ClicktheButton2():
window.destroy()
btn1 = Button(window, text="Quit", command = ClicktheButton2)
btn1.grid(column=400, row=400)
window.mainloop()
You have to change text in mylabel3 in the same why as you change text in myLabel - and even in the same place. I don't know why you have problem with this.
myLabel.configure(text = "{0}+{1}=".format(x,y))
mylabel3.configure(text="{0} of {1} correct".format(correct, correct+incorrect))
from tkinter import ttk, simpledialog
import tkinter as tk
from tkinter import *
root = Tk()
root.resizable(0, 0)
root.title("Sorting and Searching Algorithm")
root.configure(bg='#ff8080')
root.geometry("750x550")
def arrays():
v = IntVar()
for widget in root.winfo_children():
widget.destroy()
def close():
for widget in root.winfo_children():
widget.destroy()
arrays()
titleFrame = Frame(root)
titleFrame.grid(row=0)
radioFrame = Frame(root)
radioFrame.grid(padx=350, pady=100)
inputFrame = tk.Frame(root, bg='#ff8080')
inputFrame.grid()
buttonFrame = Frame(root)
buttonFrame.grid()
Title = tk.Label(titleFrame, bg='#ff8080', text="Enter The Number of Elements In The Array", font="-weight bold")
Title.grid()
global NUMBER_OF_ENTRIES
NUMBER_OF_ENTRIES = Entry(inputFrame)
NUMBER_OF_ENTRIES.grid(row=0, column=1, sticky=E, ipadx=10, ipady=10,padx=10, pady=10)
if NUMBER_OF_ENTRIES == int:
print("Working")
else:
print("Please Enter a Integer Value")
global num
num = 0
#global NUMBER_OF_ENTRIES
#NUMBER_OF_ENTRIES = simpledialog.askinteger("Please Enter", "Enter The Number of Elements In The Array")
global alist
alist = []
for i in range (0, NUMBER_OF_ENTRIES):
num = simpledialog.askinteger("Please Enter" ,"Enter The Entries In Array Element " + str(i))
alist = alist + [ num ]
calculate = ttk.Button(buttonFrame, text="Proceed", command=entries)
calculate.grid(row=4, column=0, sticky=E + S, ipadx=10, ipady=10)
arrays()
root.mainloop()
I am trying to make it so when a user inputs a integer number into the Entry input box it stores into the variable NUMBER_OF_ENTRIES. After it stores it, it then proceeds to use the value in the further conditionals.
But I am getting an issue when I try to compile it.
Because it's not an integer. NUMBER_OF_ENTRIES is of type <class 'tkinter.Entry'>.
The usual way to do this is to associate the entry with a StringVar() which will reflect whatever is typed into the entry.
The text entered into an entry is still text so you'll have to convert it to int explicitly.
See The Tkinter Entry Widget.
I can't generate the number because I get the error NameError: name 'z' is not defined.
import tkinter as tk
from random import randint
def randomize():
z.set ( randint(x.get(),y.get()))
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root)
enterY = tk.Entry(root)
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()
I need help to resolve the error
You have 2 problems here.
One. You are missing z = tk.Intvar() in the global namespace.
Two. You need to assign each entry field one of the IntVar()'s.
Keep in mind that you are not validating the entry fields so if someone types anything other than a whole number you will run into an error.
Take a look at this code.
import tkinter as tk
from random import randint
def randomize():
z.set(randint(x.get(),y.get()))
print(z.get()) # added print statement to verify results.
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
z = tk.IntVar() # added IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root, textvariable=x) # added textvariable
enterY = tk.Entry(root, textvariable=y) # added textvariable
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.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 want to make a dictionary by using a GUI, I was thinking of making two entries, one for the object and the other for the key. And I want to make a button that execute the information and add it to the empty dictionary.
from tkinter import *
fL = {}
def commando(fL):
fL.update({x:int(y)})
root = Tk()
root.title("Spam Words")
label_1 = Label(root, text="Say a word: ", bg="#333333", fg="white")
label_2 = Label(root, text="Give it a value, 1-10:", bg="#333333", fg="white")
entry_1 = Entry(root, textvariable=x)
entry_2 = Entry(root, textvariable=y)
label_1.grid(row=1)
label_2.grid(row=3)
entry_1.grid(row=2, column=0)
entry_2.grid(row=4, column=0)
but = Button(root, text="Execute", bg="#333333", fg="white", command=commando)
but.grid(row=5, column=0)
root.mainloop()
I want to use that dictionary later in my main program. You see if it would be a function, I would just go in IDLE and do..
def forbiddenOrd():
fL = {}
uppdate = True
while uppdate:
x = input('Object')
y = input('Key')
if x == 'Klar':
break
else:
fL.update({x:int(y)})
return fL
And then just use the function further on in my program
Any suggestions?
I appreciate it. Thank you
You are close to achieving what you want. There are a few modifications that need to be made. First, lets start with the entry boxes entry_1 and entry_2. Using a text variable like you did is a good approach; however I did not see them defined, so here they are:
x = StringVar()
y = StringVar()
Next, we need to change how you call the commando function and what parameters you pass though it. I want to pass the x and y values though, but I can't do this by just using something like command=commando(x.get(), y.get()), I need to use lambda as follows:
but = Button(root, text="Execute", bg="#333333", fg="white", command=lambda :commando(x.get(), y.get()))
Now why did I pass the values x and y as x.get() and y.get()? In order to get the values from a tkinter variable such as x and y, we need to use .get().
Finally, let's fix the commando function. You cannot use it as you did with fL being the parameter. This is because any parameter you set there becomes a private variable to that function even if it appears elsewhere in you code. In other words, defining a function as def commando(fL): will prevent the fL dictionary outside the function from being assessed within commando. How do you fix this? Use different parameters. Since we are passing x and y into the function, let's use those as parameter names. This is how our function looks now:
def commando(x, y):
fL.update({x:int(y)})
This will create new items in your dictionary. Here is the completed code:
from tkinter import *
fL = {}
def commando(x, y):
fL.update({x:int(y)}) # Please note that these x and y vars are private to this function. They are not the x and y vars as defined below.
print(fL)
root = Tk()
root.title("Spam Words")
x = StringVar() # Creating the variables that will get the user's input.
y = StringVar()
label_1 = Label(root, text="Say a word: ", bg="#333333", fg="white")
label_2 = Label(root, text="Give it a value, 1-10:", bg="#333333", fg="white")
entry_1 = Entry(root, textvariable=x)
entry_2 = Entry(root, textvariable=y)
label_1.grid(row=1)
label_2.grid(row=3)
entry_1.grid(row=2, column=0)
entry_2.grid(row=4, column=0)
but = Button(root, text="Execute", bg="#333333", fg="white", command=lambda :commando(x.get(), y.get())) # Note the use of lambda and the x and y variables.
but.grid(row=5, column=0)
root.mainloop()