Entry and result box calculator in Tkinter [duplicate] - python

This question already has answers here:
Tkinter: AttributeError: NoneType object has no attribute <attribute name>
(4 answers)
Closed 2 years ago.
I am a very very very beginner with programming languages, and now I started learning python, for basic I have learned it and now I just started trying to make something like a simple calculator with a Tkinter. here I am trying to make a simple calculator with 'Entry' and 'Button', but I have difficulty with what to expect.
what I want in my application is: how to combine or add values from the first and second entry fields with the button in question (+), then after the button is clicked the results appear in the box entry next to the (+) button.
I know that there have been many questions here with similar questions (Entry widgets etc) but I am really a beginner and have not gotten any answers by looking at the questions that were already in this forum.
sorry for this beginner question, and I beg for your help.
import tkinter as tk
from tkinter import *
root = tk.Tk() #main windownya
root.geometry("300x300")
root.title("Little Calc")
#Label
Label(root, text="Input First Number: ").grid(row=0, column=0)
Label(root, text="Input Second Number: ").grid(row=1, column=0)
Label(root, text="Choose Addition: ").grid(row=2, column=0)
Label(root, text="Result: ").grid(row=2, column=1)
#Entry
firstnumb = Entry(textvariable=IntVar()).grid(row=0, column=1)
secnumb = Entry(textvariable=IntVar()).grid(row=1, column=1)
#Plus Button
plus_button = Button(root, text="+", command=lambda: firstnumb.get()+secnumb.get(), width=6, height=1).grid(row=3, column=0)
plusresult = Entry(plus_button).grid(row=3, column=1)
root.mainloop()

When I run your code, I get a nullPointerException here:
plus_button = Button(root, text="+", command=lambda: firstnumb.get()+secnumb.get(), width=6, height=1).grid(row=3, column=0)
Why does this happen? You use the get() method on firstnumb and secnumb, those variables are defines as:
firstnumb = Entry(textvariable=IntVar()).grid(row=0, column=1)
secnumb = Entry(textvariable=IntVar()).grid(row=1, column=1)
And both these variables have null as value instead of the Entry object that you would want. This happens because you also use the grid() method in your variable declaration and this method returns null. Doing this in two steps fixes your problem.
firstnumb = Entry(textvariable=IntVar())
firstnumb.grid(row=0, column=1)
secnumb = Entry(textvariable=IntVar())
secnumb.grid(row=1, column=1)
When I now click the "+" button no error occurs but the result is also not yet displayed. I advise you to make a new function where you put this code: firstnumb.get()+secnumb.get(), width=6, height=1).grid(row=3, column=0 and the code to display the result.
Also, note that get() will return a string, make sure you first cast it to an int or float before adding both values. If you don't do that, 10 + 15 will give 1015.

Related

Tkinter SyntaxError: keyword argument repeated: state (how to make a button one time clickable?)

from tkinter import *
def Click():
label = Label(root, text="You clicked it")
label.pack()
root = Tk()
label2 = Label(root, text="You can only click one time")
Button = Button(root, text="Click me", padx=20, pady=20, state=NORMAL,
command=Click,state=DISABLED)
Button.pack()
label2.pack()
root.mainloop()
Because I use state 2 times I am getting this error:
SyntaxError: keyword argument repeated: state
How can I fix this error and make a button that can be clicked one time?
This should do what you want. The idea is to update the button's state from within the click handler function.
FYI, star imports can cause trouble and are best avoided, so I've done that here. I've also changed some variable names to use lowercase, since capitalized names are typically reserved for class objects in Python (things like Label and Tk, for instance!)
import tkinter as tk
def click():
label = tk.Label(root, text="You clicked it")
label.pack()
button.config(state=tk.DISABLED) # disable the button here
root = tk.Tk()
label2 = tk.Label(root, text="You can only click one time")
button = tk.Button(root, text="Click me", padx=20, pady=20, command=click)
button.pack()
label2.pack()
root.mainloop()
Bonus Round - if you want to update the existing label (label2, that is) instead of creating a new label, you can also accomplish this with config
def click():
label2.config(text="You clicked it") # update the existing label
button.config(state=tk.DISABLED) # disable the button here

Can someone help me with parameters in tkinter "command" [duplicate]

This question already has an answer here:
Tkinter assign button command in a for loop with lambda [duplicate]
(1 answer)
Closed 1 year ago.
I'm trying to make a little file explorer with just buttons, I'm still in the early stages and want to make a function prints which button was pressed and came up with this:
import tkinter as tk
buttons = []
window = tk.Tk()
window.geometry("200x100")
def open(button):
print(button)
def list(titles):
i=0
while i<(len(titles)):
btn = tk.Button(text=titles[i], width=20, command=lambda: open(i))
buttons.append(btn)
buttons[i].grid(row=i, column=1)
print(f"adding {titles[i]}")
i=i+1
list(["title1", "title2", "title3"])
window.mainloop()
There's one problem: It always prints 3. I think I know what the problem is, i always stays 3 after generating the button so it passes 3 to the function, but I don't know how to solve it.
I used the lambda cuz I cant pass parameters just using open(i) and found the lambda-solution to that on this question .
Can someone help?
Tnx!
Because it over writes the commands on one button when you assign it again. Do:
import tkinter as tk
buttons = []
window = tk.Tk()
window.geometry("200x100")
def open(button):
print(button)
def list(titles):
btn = tk.Button(text=titles[0], width=20, command=lambda: open(1))
buttons.append(btn)
buttons[0].grid(row=1, column=1)
print(f"adding {titles[0]}")
btn = tk.Button(text=titles[1], width=20, command=lambda: open(2))
buttons.append(btn)
buttons[1].grid(row=2, column=1)
print(f"adding {titles[1]}")
btn = tk.Button(text=titles[2], width=20, command=lambda: open(2))
buttons.append(btn)
buttons[2].grid(row=3, column=1)
print(f"adding {titles[2]}")
list(["title1", "title2", "title3"])
window.mainloop()

how do i send a int value typed in a text-entry box to a mathematical expression?

my name is VĂ­tor. I'm totally new in programming, it is my second or third day in self learling python. I'm trying to build a metabolical rate calculator, it is the first thing that i could iamgine to do, i know about nothing from python. Then, i did it, but only stay in text editor (im using vs code), if i change the value in code, and run, i get the right value in terminal. But im tryint to operate it by a GUI, and i dont know how i type a numeric value in a text box, and this value are changed in my writed recipe. Ill show all my code from now, sorry for the weird words and long code, i'm really new in programming world, im from B. Anyway, thanks for reading.
import tkinter as tk
from tkinter import *
#FUNCAO DO BOTAO
def click1():
typed_text1=textentry1.get()
def click2():
typed_text2=textentry2.get()
def click3():
typed_text3=textentry3.get()
####MAIN
#TOP LEVEL CONTAINER
window = Tk()
window.title("Calculadora TMB")
#CONTAINER DE FUNDO
canvas = tk.Canvas(window, height=400,width=400, bg="green") .grid()
#CONTAINER QUADRO
frame1 = tk.Frame(canvas, height=200,width=200, bg="blue") .grid(row=0, column=1)
#IMAGEM
#LABEL
Label (frame1, text="CALCULADORA TMB", fg="red") .grid(row=0, column=0)
#CAIXA DE ENTRADA DE TEXTO
textentry1=Entry(frame1) .grid(row=1, column=1)
textentry2=Entry(frame1) .grid(row=2, column=1)
textentry3=Entry(frame1) .grid(row=3, column=1)
#SEND INPUT BUTTON
okbutton=tk.Button(frame1,text='Send', command=lambda:[click1(),click2(),click3()]) .grid(row=4, column=0)
#CANCEL BUTTON
cancelbutton=tk.Button(frame1,text='Cancel') .grid(row=5, column=0)
#OUTPUT TEXT
output= Text(frame1) .grid(row=6, column=0, padx=0.8, pady=0.8, columnspan=2)
#VARIABLES
Massa_corporal=66
Estatura=167
Idade=66
#RECIPES
Formula_HB_Homem=66.473+(13.752*Massa_corporal)+(5.003*Estatura)-(6.755*Idade)
Formula_HB_Mulher=655.1+(9.563*Massa_corporal)+(1.850*Estatura)-(4.676*Idade)
Formula_Williams1_H=(60.9*Massa_corporal)-54
Formula_Williams2_H=(22.7*Massa_corporal)+495
Formula_Williams3_H=(17.5*Massa_corporal)+651
Formula_Williams4_H=(15.3*Massa_corporal)+679
Formula_Williams5_H=(11.6*Massa_corporal)+879
Formula_Williams6_H=(13.5*Massa_corporal)+487
Formula_Williams1_M=(61*Massa_corporal)-51
Formula_Williams2_M=(22.5*Massa_corporal)+499
Formula_Williams3_M=(12.2*Massa_corporal)+746
Formula_Williams4_M=(14.7*Massa_corporal)+496
Formula_Williams5_M=(8.7*Massa_corporal)+829
Formula_Williams6_M=(10.5*Massa_corporal)+596
Formula_KTG=(((((1.255*Estatura)+(0.928*Massa_corporal)-64.8)*60)/1000)*24)*5
if Idade>=60:
print ((Formula_HB_Homem+Formula_Williams6_H+Formula_KTG)/3)
elif Idade>=30:
print((Formula_HB_Homem+Formula_Williams5_H+Formula_KTG)/3)
elif Idade>=18:
print((Formula_HB_Homem+Formula_Williams4_H+Formula_KTG)/3)
elif Idade>=10:
print((Formula_HB_Homem+Formula_Williams3_H+Formula_KTG)/3)
elif Idade>=3:
print((Formula_HB_Homem+Formula_Williams2_H+Formula_KTG)/3)
elif Idade>=0:
print((Formula_HB_Homem+Formula_Williams2_H+Formula_KTG)/3)
window.mainloop()```
To receive the value from a widget, you would want to use the get() function. The get() function will return whatever is in the text-box. See this page for more from the documentation.
You should also see the example on here

Tkinter: Updating Label Contents & Button Command [duplicate]

This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 3 years ago.
I have the following code with several problems. The first of which is the createUser() command will run immediately after the window appears.
The second is my button tied to that command will not run the command itself (I have tested this by attempting to print a simple string back into IDLE).
The last problem I seem to have is my label does not update when I set the variable to different contents, even when .set() is used outside of the command.
root = tk.Tk()
root.title("Sign In Screen")
tk.Label(root,text="Username: ",font="Arial").grid(row=0,column=0)
userIDEntry = tk.Entry(root)
userIDEntry.grid(row=0,column=1)
tk.Label(root,text="Password: ",font="Arial").grid(row=1,column=0)
passwordEntry = tk.Entry(root)
passwordEntry.grid(row=1,column=1)
tk.Label(root,text="Confirm Password: ",font="Arial").grid(row=2,column=0)
passwordConfirm = tk.Entry(root)
passwordConfirm.grid(row=2,column=1)
def createAccount():
if passwordEntry.get() == passwordConfirm.get():
exampleFunction() #doesntwork
else:
var1.set("Passwords do not match!")
root.update()
var1 = tk.StringVar()
var1.set("")
tk.Button(root,text="CREATE ACCOUNT",font="Arial",command=createAccount()).grid(row=3,column=0,columnspan=2)
tk.Label(root,textvariable=var1).grid(row=4,column=0,columnspan=2)
root.mainloop()
I hope someone can help me out, I'm trying to teach myself Tkinter and can't stop running into small issues like these.
tkinter has some peculiar syntax (similar to threading). You should specify command=function and not command=function(). This will solve your first two issues. In fact after I ran it with some minor adjustments it worked (I think) to accomplish what you wanted for updating the variable as well!
import tkinter as tk
root = tk.Tk()
root.title("Sign In Screen")
tk.Label(root, text="Username: ", font="Arial").grid(row=0, column=0)
userIDEntry = tk.Entry(root)
userIDEntry.grid(row=0, column=1)
tk.Label(root, text="Password: ", font="Arial").grid(row=1, column=0)
passwordEntry = tk.Entry(root)
passwordEntry.grid(row=1, column=1)
tk.Label(root, text="Confirm Password: ", font="Arial").grid(row=2, column=0)
passwordConfirm = tk.Entry(root)
passwordConfirm.grid(row=2, column=1)
def createAccount():
if passwordEntry.get() == passwordConfirm.get():
print('thing') # your function was not included in post
else:
var1.set("Passwords do not match!")
root.update()
var1 = tk.StringVar()
var1.set("")
tk.Button(root, text="CREATE ACCOUNT", font="Arial", command=createAccount).grid(row=3, column=0, columnspan=2) # removed ()
tk.Label(root, textvariable=var1).grid(row=4, column=0, columnspan=2)
root.mainloop()

Python 3 Tkinter appending label to print user input from entry label

Hey guys I have just started learning about GUI's and in particular just started using tkinter. I have spent hours searching forums for what I believe should be an obvious and simple solution and found a few people asking similar questions but i failed to understand the solutions.
Basically I am just trying to get the user to input a letter with an entry widget and display that on a label when the go button is pressed. If anyone could explain to me how to do this I would be extremely grateful.
Here's the code I have written:
#!/usr/bin/env python3
from tkinter import*
from tkinter import ttk
import random
root = Tk()
root.title('test')
frame = ttk.Frame(root, padding='3 3 12 12 ')
frame.grid(column=0, row=0, sticky=(N, W, E, S))
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
letter = StringVar()
def gobutton(*args):
print_label['text'] += letter
print_label = ttk.Label(frame, text="")
print_label.grid(column=1, row=1, sticky=N)
letter_entry = ttk.Entry(frame, width=7, textvariable=letter)
letter_entry.grid(column=1, row=2, sticky=S)
g_button = ttk.Button(frame, width=7, text='GO', command=gobutton)
g_button.grid(column=3, row=3, sticky=S)
for child in frame.winfo_children():
child.grid_configure(padx=5, pady=5)
letter_entry.focus() #WHAT DOES THIS DO?
root.bind('<Return>', gobutton)
root.mainloop()
You should .get() what StringVar contains when button is clicked.
def gobutton(): #if you don't plan to pass any parameters, *args is unnecesarry
print_label['text'] += letter.get()
Also, for this program, using a StringVar a little bit overkill. You can easily go for Entry.get() to get what entry contains. Below code demonstrates how to use get() method with a quite simple(and a little bit dirty) code.
def getMethod():
lbl.configure(text=ent.get())
#or
#lbl["text"] = ent.get()
root = tk.Tk()
tk.Button(root, text="Get Entry", command=getMethod).pack()
ent = tk.Entry(root)
lbl = tk.Label(root, text = "Before click")
lbl.pack()
ent.pack()
root.mainloop()
.focus() is an alias for .focus_set() method.
Moves the keyboard focus to this widget. This means that all keyboard
events sent to the application will be routed to this widget.

Categories

Resources