Tkinter: Updating Label Contents & Button Command [duplicate] - python

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()

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

How to avoid TclError if I want to update the results obtained from entries instantly?

I want to add two numbers and add them and update the result instantly without using a button.
I have written this code using after() to do that.
from tkinter import *
root = Tk()
root.geometry("400x400")
label1 = Label(root, text="1st number:")
label1.grid(row=0, column=0)
label2 = Label(root, text="2nd number:")
label2.grid(row=1, column=0)
first_no = IntVar()
second_no = IntVar()
entry1 = Entry(root, textvariable=first_no)
entry1.grid(row=0, column=1)
entry2 = Entry(root, textvariable=second_no)
entry2.grid(row=1, column=1)
def auto():
try:
S = first_no.get() + second_no.get()
label3.config(text="Sum: " + str(S))
# call again after 100 ms
root.after(100, auto)
except TclError:
print("there is an Error")
label3 = Label(root)
label3.grid(row=3, column=1)
auto()
root.mainloop()
The code works well. However, if we delete the numbers in the entries using the delete or backspace keyboards this error raises: _tkinter.TclError: expected floating-point number but got "", and if I enter new values the code does not work anymore.
I wondered to know how I avoid this problem??
I found the solution. I added another root.after(100, auto) under exception TclError

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()

Copying text in tkinter from label or msgbeox

I been searching for methods to copy text to clipboard or copy the results from Tkinter gui but idk if there is a command or something
here is my code for now here the result comes in a messagebox can i copy it to clipboard
import tkinter.messagebox
import string
import random
def qs_msgbbox(): # qs_msgbbox
tkinter.messagebox.showinfo("Info", "For customer support or tip or rating contact:"
"dghaily725#gmail.com\npress the button for generated pass\nmsg will appear then copy\nthe generated password")
def gen_pass(k=9): # gen_pass
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*"
password = ''
for i in range(9):
password += random.choice(char)
tkinter.messagebox.showinfo("Password", password)
root = Tk()
root.title("Password Generator")
lbl1 = Label(root, text="Generate Password", bd=2, relief=SUNKEN, height=5, width=50, bg='black', fg='white')
lbl1.configure(font=(70))
lbl1.grid(row=0, column=2)
lbl2 = Label(root, text='For more information press the Question mark', bd=2, relief=SUNKEN, fg='red')
lbl2.configure(font=(70))
lbl2.grid(row=0, column=0, pady=10)
btn1 = Button(root, text='Press to Generate', height=5, width=50, bg='grey', command=gen_pass)
btn1.configure(font=(70))
btn1.grid(row=1, column=2, padx=460, pady=50)
btn2photo = PhotoImage(file='question.png')
btn2 = Button(root, image=btn2photo, width=30, height=30, command= qs_msgbbox)
btn2.grid(row=0, column=1)
root.mainloop()
and also just a quick small question is it better to use classes or this form
Tkinter does have a function for that, simply just
from tkinter import Tk
root = Tk()
root.clipboard_clear()
root.clipboard_append("Something to the clipboard")
root.update() # the text will stay there after the window is closed
Hope I could help
Greets
The above answer is perfectly fine. Infact its the method to do it. I read the comments, He had mentioned that it could only take in string. That is completely false. It can also take in functions. For example..
import tkinter as tk
root = tk.Tk()
#creating a entry Widget.(Labels are fine as well)
entry = tk.Entry(root)
entry.pack()
#NOW if you want to copy the whole string inside the above entry box after you
typed in #
def copy ():#assign this function to any button or any actions
root.clipboard_clear()
root.clipboard_append(entry.get()) #get anything from the entry widget.
root.mainloop()
Hoping this was helpful

Entry and result box calculator in Tkinter [duplicate]

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.

Categories

Resources