I want to refresh the the password Label every time the refresh button is pressed.
I tried the .config but it doesn't work.
import random
import string
import tkinter.messagebox
from tkinter import *
def get_all_passwords():
with open('Passwords.txt') as f:
global password_Text
password_Text = f.read()
f.close()
def main_window():
def all_passwords_text():
global password_Text
All_passwords_label.config(text=password_Text)
All_passwords_label = tkinter.Label(
window,
text=password_Text,
foreground="black",
background="white",
width=25,
)
password_label = tkinter.Label(
text=password,
foreground="white",
background="black",
width=20,
)
save_button = tk.Button(
text='save',
width=10,
cursor='hand1',
bg='light gray',
command=lambda:[write_password_to_txt(), All_passwords_label, window.update()]
)
refresh_button = tk.Button(
text='Refresh',
width=20,
bg="white",
fg="black",
command=all_passwords_text
)
All_passwords_label.pack(side='right')
password_label.pack()
safe_entry.pack()
save_button.pack()
refresh_button.pack()
window.mainloop()
random_password()
main_window()
import tkinter as tk # avoid star imports; this can lead to namespace pollution
import tkinter.messagebox
# other imports, etc.
# declare a StringVar to store the label text
password_var = tk.StringVar()
def get_all_passwords():
with open('Passwords.txt') as f:
password_Text = f.read()
password_var.set(password_text) # update 'password_var'
# f.close() - you don't need this when using 'with'
# see link below
"Context Managers and Python's with Statement"
# add a 'textvariable' binding to your label
# the label text will update whenever the variable is set
All_passwords_label = tk.Label(
window,
text=password_Text,
textvariable=password_var # add this!
foreground="black",
background="white",
width=25,
)
Now any time you call get_all_passwords() the label text of All_passwords_label should update.
Note that you no longer need the all_passwords_text function at all, and you don't need to use globals either.
Related
How do I use user input to retrieve an image, and display it on the screen? I have the user input field in Tkinter, and I do not know how to get that to go to my folder, and get the image to show up on the same screen.
EDIT: I was able to get the path to show on the screen, but now I don't know how to get the actual image to show up from that path inside the frame... I do not know how to link this path to have the program display the image, i.e. myimage1 from my folder.
from tkinter import *
from PIL import ImageTk,Image
from tkinter import ttk
from tkinter import filedialog
root = Tk()
root.title("Images")
root.iconbitmap(r'C:\Users\hadhikari\example\Takumi_Logo.ico')
button_quit = Button(root, text= "Exit Program", command=root.quit)
button_quit.pack()
e= Entry(root, width=50, bg="light blue", borderwidth=3)
e.pack()
e.insert(0," ")
def myClick():
link = "r'C:\\Users\\hadhikari\\example\\" + e.get()
myLabel1 = Label(root, text=link)
myLabel1.pack()
myButton = Button(root, text="Scan Part Number", command=myClick,
bg="pink", fg="white")
myButton.pack()
#my_img = ImageTk.PhotoImage(Image.open('link'))
#my_Label = Label(image=my_img)
#my_Label.pack()
#def getText():
# inputtedtext = entrybox.get()
#entrybox = Entry(root)
#entrybox.pack()
#btn = Button(root, text="Submit", command=getText)
#btn.pack()
frame = LabelFrame(root, padx=100, pady=100)
frame.pack(padx=50, pady=50)
root.mainloop()
As suggested in the comments, maybe using Tkinter's askopenfilename dialog might be a better choice than hardcoding the filepath, and letting the user input the filename.
But, first of all, let's fix the code following your intentions. Most of the part on how to properly set up a Tkinter Label, and dynamically place images in that, can be easily found, for example in this Q&A. Basically, you want to put the "update routine" inside your myClick method:
from tkinter import *
from PIL import Image, ImageTk
# How to properly set up Tkinter label with dynamically changeable
# ImageTk.PhotoImage: https://stackoverflow.com/a/3482156/11089932
root = Tk()
button_quit = Button(root, text='Exit Program', command=root.quit)
button_quit.pack()
e = Entry(root, width=50, bg='light blue', borderwidth=3)
e.pack()
e.insert(0, '')
my_label = Label()
my_label.pack()
def myClick():
link = r'your/path/goes/here' + e.get()
my_img = ImageTk.PhotoImage(Image.open(link))
my_label.configure(image=my_img)
my_label.image = my_img
myButton = Button(root, text='Scan Part Number', command=myClick,
bg='pink', fg='white')
myButton.pack()
root.mainloop()
Program at startup:
Opening the first image:
Opening another image:
Now, regarding the askopenfilename dialog, we get rid of the Entry widget, and simply open the dialog inside the myClick method:
from tkinter import *
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk
# How to properly set up Tkinter label with dynamically changeable
# ImageTk.PhotoImage: https://stackoverflow.com/a/3482156/11089932
root = Tk()
button_quit = Button(root, text='Exit Program', command=root.quit)
button_quit.pack()
my_label = Label()
my_label.pack()
def myClick():
link = askopenfilename()
my_img = ImageTk.PhotoImage(Image.open(link))
my_label.configure(image=my_img)
my_label.image = my_img
myButton = Button(root, text='Scan Part Number', command=myClick,
bg='pink', fg='white')
myButton.pack()
root.mainloop()
Program at startup:
Opening the first image (dialog):
Opening the first image (display):
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.19041-SP0
Python: 3.9.1
PyCharm: 2021.1.3
Pillow: 8.3.1
----------------------------------------
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
This is my code:
import pandas as pd
from tkinter import *
master = Tk()
label1= Label(master, text='Department')
label1.grid(row=0, column=0)
textBox = Text(master, height=1, width=10)
textBox.grid(row=0, column=1)
def retrieve_input():
Department = textBox.get("1.0","end-1c")
fileread = pd.read_csv('50.csv', encoding='latin-1')
filevalue = fileread.loc[fileread['Customer'].str.contains(Department, na=False)]
def printSomething():
label = Label(master, textvariable=filevalue)
label.grid(row=3, column=1)
button1 = Button(master,text="Show Values", command=lambda: retrieve_input())
button1.grid(row=2, column=1)
mainloop( )
I have searched around Stack Overflow of how to do this, and was able to construct my code up until this point, However when I click the Show values button, nothing happens. I could find nowhere online that helped address this issue. Is there something fundamentally wrong with my code? Using Python 3.7
You define a nested printSomething function that would display something, but you never call that function.
This would fix that problem:
def retrieve_input():
Department = textBox.get("1.0","end-1c")
fileread = pd.read_csv('50.csv', encoding='latin-1')
filevalue = fileread.loc[fileread['Customer'].str.contains("Lam Dep", na=False)]
def printSomething():
label = Label(master, textvariable=filevalue)
label.grid(row=3, column=1)
printSomething()
But I'm not sure why you need the function in the first place; you can just do this:
def retrieve_input():
Department = textBox.get("1.0","end-1c")
fileread = pd.read_csv('50.csv', encoding='latin-1')
filevalue = fileread.loc[fileread['Customer'].str.contains("Lam Dep", na=False)]
label = Label(master, textvariable=filevalue)
label.grid(row=3, column=1)
But you have a second problem: You're trying to set the textvariable=filevalue, but that doesn't make any sense.
The textvariable has to be a tkinter.StringVar instance, not a plain old Python string. You can then set the StringVar to hold your string.
filevar = StringVar()
filevar.set(filevalue)
label = Label(master, textvariable=filevar)
label.grid(row=3, column=1)
… or just pass the text in directly, without a tkinter variable:
label = Label(master, text=filevalue)
label.grid(row=3, column=1)
There's still one more problem: Every time you call retrieveInput, it's going to create a new Label and grid it in front of whatever used to be there, but you never delete the old ones. So if you press the button over and over again, there will be a whole stack of invisible widgets just wasting resources.
It probably makes more sense to move the label creation to the global scope, just like the text box and the other label, and replace its text in this function, instead of creating a new label each time.
Using a StringVar is the simplest way to do this:
# ...
textBox = Text(master, height=1, width=10)
textBox.grid(row=0, column=1)
fileVar = StringVar()
fileLabel = Label(master, textvariable=fileVar)
fileLabel.grid(row=3, column=1)
def retrieve_input():
Department = textBox.get("1.0","end-1c")
fileread = pd.read_csv('50.csv', encoding='latin-1')
filevalue = fileread.loc[fileread['Customer'].str.contains("Lam Dep", na=False)]
fileVar.set(filevalue)
# ...
You may have other bugs in your code, but I think if you fix these three, you'll at least be pretty close to everything working.
Considering you are running Python 3.7, as you said, the following code will solve your problem:
import pandas as pd
from tkinter import *
master = Tk()
label1= Label(master, text='Department')
label1.grid(row=0, column=0)
textBox = Text(master, height=1, width=10)
textBox.grid(row=0, column=1)
def retrieve_input():
global text
department = textBox.get("1.0","end-1c")
fileread = pd.read_csv('50.csv', encoding='latin-1')
filevalue = fileread.loc[fileread['Customer'].str.contains("Lam Dep", na=False)]
text.set(filevalue)
button1 = Button(master,text="Show Values", command=retrieve_input)
button1.grid(row=2, column=1)
text = StringVar()
label = Label(master, textvariable=text)
label.grid(row=0, column=1)
mainloop()
You are facing these problems:
You are defining an inner function printSomething which is never called.
Even if you were calling printSomething you are going to create a new Label every time you press button1.
In this as, you don't need to use lambda to pass the callback that will be executed, you can simply pass command=retrieve_input
The simplest solution might be to define a StringVar (text) which is going to be associated with a Label (label), and when you press the button button1 you update call the method set on that variable text.
so i'm trying to create a code which when each button is clicked it will make that button fit a certain style but with changes to the name, however my current code will replace the button you click and them when you click on another it disables the last one you clicked permanently is there anyway to make it so that the buttons all use the same function but dont get disabled when you activate another button?
from tkinter import *
MainWindow = Tk()
def SquadInfoBttnFull():
global SquadFullBttn
SquadFullBttn = Toplevel(MainWindow)
SquadFullBttn.geometry("658x600")
# -- unit buttons -- #
for i in range(10):
Unit_Button = Button(SquadFullBttn, text="EMPTY", width=8, height=6)
Unit_Button.grid(row = 0, column = i)
Unit_Button.bind("<Button-1>", UnitFill)
def SquadInfoBttn():
InfoBttn = Button(MainWindow, wraplength=50, justify=LEFT, text="SquadInfo Here", width=100, command=SquadInfoBttnFull)
InfoBttn.grid(row=0, column=0, sticky=W)
def UnitInfoBttn():
UnitInfo = Toplevel(SquadFullBttn)
UnitInfo.geometry("300x200")
def UnitFill(event):
global photo
photo = PhotoImage(file="csmSingle.png")
btn = event.widget
grid_info = event.widget.grid_info()
btn = Button(SquadFullBttn, text="UNIT", image=photo, width=58, height=93, command=UnitInfoBttn, compound = TOP)
btn.grid(row=grid_info["row"], column=grid_info["column"], sticky=E)
SquadInfoBttn()
MainWindow.mainloop()
You are trying to make changes to the existing button and not create a new one. Also, you don't need to create a new instance of PhotoImage every time. The following code works for me:
from tkinter import *
MainWindow = Tk()
photo = PhotoImage(file="csmSingle.png")
def SquadInfoBttnFull():
global SquadFullBttn
SquadFullBttn = Toplevel(MainWindow)
SquadFullBttn.geometry("658x600")
# -- unit buttons -- #
for i in range(10):
Unit_Button = Button(SquadFullBttn, text="EMPTY", width=8, height=6)
Unit_Button.grid(row = 0, column = i)
Unit_Button.bind("<Button-1>", UnitFill)
def SquadInfoBttn():
InfoBttn = Button(MainWindow, wraplength=50, justify=LEFT, text="SquadInfo Here", width=100, command=SquadInfoBttnFull)
InfoBttn.grid(row=0, column=0, sticky=W)
def UnitInfoBttn():
UnitInfo = Toplevel(SquadFullBttn)
UnitInfo.geometry("300x200")
def UnitFill(event):
btn = event.widget
grid_info = event.widget.grid_info()
btn.config(text="UNIT", image=photo, width=58, height=93, command=UnitInfoBttn, compound = TOP)
btn.grid(row=grid_info["row"], column=grid_info["column"], sticky=E)
SquadInfoBttn()
MainWindow.mainloop()
from Tkinter import *
import time
#Tkinter stuff
class App(object):
def __init__(self):
self.root = Tk()
self.labeltitle = Label(root, text="", fg="black", font="Helvetica 40 underline bold")
self.labeltitle.pack()
self.labelstep = Label(root, text="", fg="black", font="Helvetica 30 bold")
self.labelstep.pack()
self.labeldesc = Label(root, text="", fg="black", font="Helvetica 30 bold")
self.labeldesc.pack()
self.labeltime = Label(root, text="", fg="black", font="Helvetica 70")
self.labeltime.pack()
self.labelweight = Label(root, text="", fg="black", font="Helvetica 25")
self.labelweight.pack()
self.labelspeed = Label(root, text="", fg="black", font="Helvetica 20")
self.labelspeed.pack()
self.labeltemp = Label(root, text="", fg="black", font="Helvetica 20")
self.labeltemp.pack()
self.button = Button(root, text='Close recipe', width=25, command=root.destroy)
self.button.pack()
def Update(self, label, change):
label.config(text=str(change))
def main():
app = App()
app.mainloop()
if __name__ == "__main__":
main()
I'm trying to create a recipe display which will show the step, instructions, weight and other variables on a screen in a Tkinter GUI.
However, I do not know how to update the GUI to change with each new step of the recipe, as the content has to be dynamically updated based on user input (taken from a server). How can I achieve updating of the GUI's other elements based on the change in steps?
You can use after() to run function after (for example) 1000 miliseconds (1 second) to do something and update text on labels. This function can run itself after 1000 miliseconds again (and again).
It is example with current time
from Tkinter import *
import datetime
root = Tk()
lab = Label(root)
lab.pack()
def clock():
time = datetime.datetime.now().strftime("Time: %H:%M:%S")
lab.config(text=time)
#lab['text'] = time
root.after(1000, clock) # run itself again after 1000 ms
# run first time
clock()
root.mainloop()
BTW: you could use StringVar as sundar nataraj Сундар suggested
EDIT: (2022.01.01)
Updated to Python 3 with other changes suggested by PEP 8 -- Style Guide for Python Code
import tkinter as tk # PEP8: `import *` is not preferred
import datetime
# --- functions ---
# PEP8: all functions before main code
# PEP8: `lower_case_name` for funcitons
# PEP8: verb as function's name
def update_clock():
# get current time as text
current_time = datetime.datetime.now().strftime("Time: %H:%M:%S")
# udpate text in Label
lab.config(text=current_time)
#lab['text'] = current_time
# run itself again after 1000 ms
root.after(1000, update_clock)
# --- main ---
root = tk.Tk()
lab = tk.Label(root)
lab.pack()
# run first time at once
update_clock()
# run furst time after 1000ms (1s)
#root.after(1000, update_clock)
root.mainloop()
if you want to change label dynamically
self.dynamiclabel=StringVar()
self.labeltitle = Label(root, text=self.dynamiclabel, fg="black", font="Helvetica 40 underline bold")
self.dyanamiclabel.set("this label updates upon change")
self.labeltitle.pack()
when ever you get new value then just use .set()
self.dyanamiclabel.set("Hurrray! i got changed")
this apply to all the labels.To know more read this docs
If you are using labels, then you can use this:
label = tk.Label(self.frame, bg="green", text="something")
label.place(rely=0, relx=0.05, relwidth=0.9, relheight=0.15)
refresh = tk.Button(frame, bg="white", text="Refreshbutton",command=change_text)
refresh.pack(rely=0, relx=0.05, relwidth=0.9, relheight=0.15)
def change_text()
label["text"] = "something else"
Works fine for me, but it is dependent on the need of a button press.
I added a process bar in my window, and change its value according to randint for every 1 second using the update function:
from random import randint
def update():
mpb["value"] = randint(0, 100) # take process bar for example
window.after(1000, update)
update()
window.mainloop()
I wrote an example with Python 3.7
from tkinter import *
def firstFrame(window):
global first_frame
first_frame = Frame(window)
first_frame.place(in_=window, anchor="c", relx=.5, rely=.5)
Label(first_frame, text="ATTENTION !").grid(row=1,column=1,columnspan=3)
def secondFrame(window):
global second_frame
second_frame= Frame(window, highlightbackground=color_green, highlightcolor=color_green, highlightthickness=3)
second_frame.place(in_=window, anchor="c", relx=.5, rely=.5)
Label(second_frame, text="This is second frame.").grid(row=1, column=1, columnspan=3, padx=25, pady=(15, 0))
window = Tk()
window.title('Some Title')
window.attributes("-fullscreen", False)
window.resizable(width=True, height=True)
window.geometry('300x200')
firstFrame(window)
secondFrame(window)
first_frame.tkraise()
window.after(5000, lambda: first_frame.destroy()) # you can try different things here
window.mainloop()
Use root.config() and add a way to run