Update Label in Tkinter when calling function - python

I have a Tkinter GUI and I would like to update the status of the script in a Label, writing which function is being called, but I am having problems with that.
I have already seen many answers on here, but still I cant come to a solution. This is the part of the code that I am working on:
run_script(username, password):
text = StringVar()
text.set('')
l=Label(master, text=text, fg='blue')
l.grid(row=6) #I would like the Label in the row 6
l.pack()
text.set('calling my function1')
my_file.my_function1(username, password)
text.set('calling my function2')
my_file.my_function2()
master = Tk()
username = Entry(master, name='username', width=30)
password = Entry(master, name='password', show='*', width=30)
username.grid(row=0, column=1, padx=10, pady=(10,2))
password.grid(row=1, column=1, padx=10, pady=2)
def call_report(username, password):
run_script(username, password)
Button(master, text='start script',
command= lambda:call_report(username.get(), password.get(),)).grid(row=6, column=1, sticky=W, pady=10)
mainloop()
The program run perfectly, just the label is not updated. Thanks

here is one way to do it, using the keyword argument textvariable:
import tkinter as tk
def run_script(username, password):
text = tk.StringVar()
text.set('')
lab = tk.Label(master, textvariable=text, fg='blue')
lab.grid(row=6)
text.set('calling my function1')
# call functions here
def call_report(username, password):
run_script(username, password)
if __name__ == '__main__':
master = tk.Tk()
username = tk.Entry(master, name='username', width=30)
password = tk.Entry(master, name='password', show='*', width=30)
username.grid(row=0, column=1, padx=10, pady=(10,2))
password.grid(row=1, column=1, padx=10, pady=2)
button = tk.Button(master, text='start script', command=lambda: call_report(username.get(), password.get(),))
button.grid(row=6, column=1, sticky=tk.W, pady=10)
master.mainloop()
Note:
The use of pack and grid geometry managers in the same widget is not encouraged.
Please import tkinter as tk: adding tk. is a small price to keep the namespace clean.

This is my solution that can be used as example:
from Tkinter import *
from time import sleep
def run_script():
text = StringVar()
l = Label(master, textvariable=text, fg='blue').grid(row=6)
text.set('calling my function1')
master.update()
sleep(2)
text.set('end of function1')
def call_report():
run_script()
if __name__ == '__main__':
master = Tk()
username = Entry(master, name='username', width=30)
password = Entry(master, name='password', show='*', width=30)
username.grid(row=0, column=1, padx=10, pady=(10,2))
password.grid(row=1, column=1, padx=10, pady=2)
button = Button(master, text='start script', command=lambda: call_report())
button.grid(row=6, column=1, sticky=W, pady=10)
master.mainloop()
I've changed text to textvariable in Label, and I added master.update(). In this way it force the GUI to redraw. Just to test if the GUI was changing, I tested with sleep. It is possible to update more time (for example before calling a function).

Related

how to add admin priviledge with tkinter

I’m coding a database management app with python tkinter packages. This API is on a NAS (network attached storage). So the users can open it from a connection and make modifications in real time.
I want to give some privilege for admin users. That means if a users log in the app, they can tick and fill entry box which is disabled for normal users.
How to do it?
Here is my try:
from tkinter import *
import tkinter as tk
from tkinter import ttk
#Initialisation
root=Tk()
root.title("Test")
#Tab creation
my_tab=ttk.Notebook(root)
my_tab.pack(expand=True, fill=tk.BOTH)
#Tab name and their creation
frames=[]
nom_des_onglets=["Main", "First tab", "Second tab"]
def admin():
global longentrie
win=Toplevel()
longentrie = StringVar()
password_msg = tk.Label(win,text="Enter password for administrator privileges")
password_msg.pack()
password_entries = tk.Entry(win,textvariable=longentrie)
password_entries.pack()
tk.Button(win,text='Enter', command=admin_privilege).pack()
def admin_privilege():
global login_value
password_admin = longentrie.get()
if password_admin == 'good':
login_value=1
else:
login_value=0
for i in range(3):
frame=ttk.Frame(my_tab) # add tab
frame.pack(fill="both")
frames.append(frame)
my_tab.add(frames[i], text=nom_des_onglets[i])
#Login button
login=tk.Button(frames[0],text="login", command=admin)
login.pack()
#special priviledge
var1 = tk.IntVar()
ts = [tk.StringVar() for _ in range(17)]
lbl7 = tk.Checkbutton(frames[1], text='Text',variable=var1, onvalue=1,offvalue=0, bg='#ececec', state='disabled')
lbl7.grid(row=0, column=0, padx=5, pady=3)
lbl1=tk.Label(frames[1], text="Name")
lbl1.grid(row=2, column=0, padx=5, pady=3)
ent7=Entry(frames[1], textvariable=ts[6])
ent7.grid(row=2, column=1, padx=5, pady=3,sticky="nsew")
lbl8=tk.Label(frames[1], text="Age")
lbl8.grid(row=3, column=0, padx=5, pady=3)
ent8=Entry(frames[1], textvariable=ts[7],state='disabled')
ent8.grid(row=3, column=1, padx=5, pady=3,sticky="nsew")
if login_value == 1:
lbl7.configure(state='normal')
ent8.configure(state='normal')
root.mainloop()
Here's an example where entering the right password does correctly change the disabled state of those two fields.
This could be refactored to be a lot less messy (better variable naming for one), but it's a start:
import tkinter as tk
from tkinter import ttk
is_admin = False
def setup_ui():
lbl7.configure(state=("normal" if is_admin else "disabled"))
ent8.configure(state=("normal" if is_admin else "disabled"))
def do_login_window():
def admin_privilege():
global is_admin
if password_var.get() == "good":
is_admin = True
setup_ui()
login_win.destroy() # Close the login box
login_win = tk.Toplevel()
password_var = tk.StringVar()
password_msg = tk.Label(login_win, text="Enter password for administrator privileges")
password_msg.pack()
password_entries = tk.Entry(login_win, textvariable=password_var)
password_entries.pack()
tk.Button(login_win, text="Enter", command=admin_privilege).pack()
# Initialisation
root = tk.Tk()
root.title("Test")
# Tab creation
my_tab = ttk.Notebook(root)
my_tab.pack(expand=True, fill=tk.BOTH)
frames = []
for name in ["Main", "First tab"]:
frame = ttk.Frame(my_tab)
frame.pack(fill="both")
frames.append(frame)
my_tab.add(frame, text=name)
# Login button
login_frame = frames[0]
login = tk.Button(login_frame, text="login", command=do_login_window)
login.pack()
# special priviledge
data_frame = frames[1]
var1 = tk.IntVar()
ts = [tk.StringVar() for _ in range(17)]
lbl7 = tk.Checkbutton(
data_frame, text="Text", variable=var1, onvalue=1, offvalue=0, bg="#ececec"
)
lbl7.grid(row=0, column=0, padx=5, pady=3)
lbl1 = tk.Label(data_frame, text="Name")
lbl1.grid(row=2, column=0, padx=5, pady=3)
ent7 = tk.Entry(data_frame, textvariable=ts[6])
ent7.grid(row=2, column=1, padx=5, pady=3, sticky="nsew")
lbl8 = tk.Label(data_frame, text="Age")
lbl8.grid(row=3, column=0, padx=5, pady=3)
ent8 = tk.Entry(data_frame, textvariable=ts[7])
ent8.grid(row=3, column=1, padx=5, pady=3, sticky="nsew")
setup_ui() # Will be called after logging in too
root.mainloop()

How can I create a tkinter Python chat app with msg feature?

I want to create a Python chat app with msg feature.
Well, I've been working on this project for a while, and I want to build a messaging app using Python tkinter with msg feature available in any PC.
The problem is that the code contains some errors.
Now I will show you the code
from threading import *
from tkinter import *
import os
window = Tk()
window.title("msg")
window.geometry("350x150+300+100")
txtYourMessage = Entry(window, width=50)
txtYourMessage.insert(0,"")
txtYourMessage.grid(row=1, column=0, padx=10, pady=10)
server = Entry(window, width=50)
server.insert(0,"")
server.grid(row=2, column=0, padx=10, pady=10)
def Message():
os.system("msg * /server:%server% %txtYourMessage%")
btnSendMessage = Button(window, text="Send", width=20, command=Message)
btnSendMessage.grid(row=3, column=0, padx=10, pady=10)
window.mainloop()
When I run the code, the code actually works but it doesn't send the message you wrote, I think the problem is in this part
txtYourMessage = Entry(window, width=50)
txtYourMessage.insert(0,"")
txtYourMessage.grid(row=1, column=0, padx=10, pady=10)
server = Entry(window, width=50)
server.insert(0,"")
server.grid(row=2, column=0, padx=10, pady=10)
def Message():
os.system("msg * /server:%server% %txtYourMessage%")
correct code
from threading import *
from tkinter import *
import os
window = Tk()
window.title("msg")
window.geometry("350x150+300+100")
txtYourMessage = Entry(window, width=50)
txtYourMessage.insert(0,"")
txtYourMessage.grid(row=1, column=0, padx=10, pady=10)
server = Entry(window, width=50)
server.insert(0,"")
server.grid(row=2, column=0, padx=10, pady=10)
def Message():
os.system(f"msg * /server:{server.get()} {txtYourMessage.get()}")
btnSendMessage = Button(window, text="Send", width=20, command=Message)
btnSendMessage.grid(row=3, column=0, padx=10, pady=10)
window.mainloop()

Why aren't my buttons properly aligned with python TKinter

I am creating a password manager which includes some buttons, but for some reason these buttons aren't aligning properly, could someone help out?
Here is the code i've done usint Tkinter for these buttons:
btn = Button(window, text="Exit Securely", command=exit)
btn.grid(column=2)
btn = Button(window, text="Add Entry", command=addEntry)
btn.grid(column=1)
btn = Button(window, text="Generate", command=run)
btn.grid(column=0)
lbl = Label(window, text="Website")
lbl.grid(row=3, column=0, padx=80)
lbl = Label(window, text="Username")
lbl.grid(row=3, column=1, padx=80)
lbl = Label(window, text="password")
lbl.grid(row=3, column=2, padx=80)
which makes my program look like this:
Any general tips or helpful links for how to make a nicer GUI would be appreciated as well, as I have been struggling with that.
As #acw1668 said if you don't specify row in grid(), it will take the next available row.
# Code to make this example work:
from tkinter import *
def addEntry():pass
def run():pass
window = Tk()
# Added `row=0` for each one of them
btn = Button(window, text="Exit Securely", command=exit)
btn.grid(row=0, column=2)
btn = Button(window, text="Add Entry", command=addEntry)
btn.grid(row=0, column=1)
btn = Button(window, text="Generate", command=run)
btn.grid(row=0, column=0)
# Changed the row to 1 for all of them
lbl = Label(window, text="Website")
lbl.grid(row=1, column=0, padx=80)
lbl = Label(window, text="Username")
lbl.grid(row=1, column=1, padx=80)
lbl = Label(window, text="password")
lbl.grid(row=1, column=2, padx=80)
By the way it is a good idea to use different names for the different buttons/labels.
I have been trying various method of aligning the widgets of tkinter in the program window lately and well I have found a better working solution to this.
In you program you have been using grid for aligning. I would say that you replace with place instead.
place will allow you to set a definite x and y coordinate for the widget and it would be easy to use.
If I alter your code accordingly, I can show you the code (after alteration) and the image of the output.
Code (After Alteration)
# Code to make this example work:
from tkinter import *
def addEntry():pass
def run():pass
window = Tk()
# Adding geometry ettig.
window.geometry('500x500')
btn = Button(window, text="Exit Securely", command=exit)
btn.place(x=410, y=20)
btn = Button(window, text="Add Entry", command=addEntry)
btn.place(x=210, y=20)
btn = Button(window, text="Generate", command=run)
btn.place(x=10, y=20)
lbl = Label(window, text="Website")
lbl.place(x=10, y=50)
lbl = Label(window, text="Username")
lbl.place(x=210, y=50)
lbl = Label(window, text="password")
lbl.place(x=410, y=50)
The Output Screen

Moving buttons/entries using grid in tkinter Python

I have just started learning tkinter and am having troubles with moving items around using grid. I am assuming this is an easy fix but I am trying to get my password entry and "generate password" button to be located much closer than they are as seen in the attached image (essentially I want everything aligned). How can I do this? I have looked on here and elsewhere but can't seem to find anything that replicates my problem.
from tkinter import *
window = Tk()
window.title("Password Manager")
window.config(padx=50, pady=50)
canvas = Canvas(height=200, width=200)
canvas.grid(column=1, row=0)
lock = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=lock)
website = Label(text="Website:")
website.grid(column=0, row=1)
email_user_name = Label(text="Email/Username:")
email_user_name.grid(column=0, row=2)
password = Label(text="Password:")
password.grid(column=0, row=3)
website_entry = Entry(width=35)
website_entry.grid(column=1, row=1, columnspan=2)
email_entry = Entry(width=35)
email_entry.grid(column=1, row=2, columnspan=2)
password_entry = Entry(width=21)
password_entry.grid(column=1, row=3)
generate_button = Button(text="Generate Password")
generate_button.grid(column=2, row=3)
add_button = Button(text="Add", width=30)
add_button.grid(column=1, row=4, columnspan=2)
window.mainloop()
You can add sticky="e" to grid(...) on the labels and sticky="w" on the entries:
from tkinter import *
window = Tk()
window.title("Password Manager")
window.config(padx=50, pady=50)
canvas = Canvas(height=200, width=200)
canvas.grid(column=1, row=0)
lock = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=lock)
website = Label(text="Website:")
website.grid(column=0, row=1, sticky="e")
email_user_name = Label(text="Email/Username:")
email_user_name.grid(column=0, row=2, sticky="e")
password = Label(text="Password:")
password.grid(column=0, row=3, sticky="e")
website_entry = Entry(width=35)
website_entry.grid(column=1, row=1, columnspan=2, sticky="w")
email_entry = Entry(width=35)
email_entry.grid(column=1, row=2, columnspan=2, sticky="w")
password_entry = Entry(width=21)
password_entry.grid(column=1, row=3, columnspan=2, sticky="w")
generate_button = Button(text="Generate Password")
generate_button.grid(column=3, row=3, sticky="w")
add_button = Button(text="Add", width=30)
add_button.grid(column=1, row=4, columnspan=2)
window.mainloop()
Note that I have added columnspan=2 to password_entry.grid(...) and moved generate_button to column 3.

Button Adjusting tkinter Python 3.8

all of my code is ready except the placement of the Quit button. I want to move to the Calculate button as much as possible, even like sticked to each other. Could you help in adjusting so the buttons will stick to each other?
from tkinter import *
window = Tk()
class MainGUI:
def __init__(self):
Label(window, text="Enter the property value: $").grid(row=1,column=1, sticky=W)
Label(window, text="Assessment Value").grid(row=2,column=1, sticky=W)
Label(window, text="Property Tax").grid(row=3,column=1, sticky=W)
self.propertyValue = StringVar()
self.assessmentValue = StringVar()
self.propertyTax = StringVar()
Entry(window, textvariable=self.propertyValue,justify=RIGHT).grid(row=1, column=2)
Button(window, text="Calculate",
command=self.calculate).grid(row=6, column=1, sticky=E)
Button(window, text="Quit",
command=self.close_window).grid(row=6, column=2, sticky=E)
Label(window, textvariable=
self.assessmentValue).grid(row=2, column=2, sticky=E)
Label(window, textvariable=
self.propertyTax).grid(row=3, column=2, sticky=E)
window.mainloop() # Create an event loop
def calculate(self):
self.assessmentValue.set("{0:10.2f}".format(float(self.propertyValue.get()) * 60 / 100))
self.propertyTax.set("{0:10.2f}".format(float(self.propertyValue.get()) * 60 / 10000 * 0.75))
def close_window(self):
window.destroy()
MainGUI()

Categories