Update text widget in tkinter from function - python

The problem:
I am trying to update the same text widget box from a function that contains some text. Instead a whole new text window appears every time.
Here is my code:
from tkinter import *
import os
#Tkinter graphics
homepage = Tk()
homepage.title("My first GUI")
# set size of window
homepage.geometry('1200x400')
# Add image file
bg = PhotoImage(file = "maxresdefault.png")
# Show image using label
label1 = Label( homepage, image = bg)
label1.place(x = 0, y = 0)
label2 = Label( homepage, text = "Test App")
label2.pack()
# Create Frame
frame1 = Frame(homepage)
frame1.pack()
#button initatiors
def buttonupdate():
S = Scrollbar(homepage)
T = Text(homepage, height=100, width=30)
T.pack()
T.pack(side=RIGHT, fill= Y)
S.pack(side = RIGHT, fill = Y)
S.config(command=T.yview)
T.insert(END, "test")
T.config(yscrollcommand=S.set, state=DISABLED)
# Static buttons
tickets30button = Button(text = "This is button 1", command=buttonupdate)
tickets30button.place(x=0, y=26)
mcibutton = Button(text = "This is button 2")
mcibutton.place(x=0, y=52)
hdebutton = Button(text = "This is button 3")
hdebutton.place(x=0, y=78)
homepage.mainloop()
Here is the result if I click on the first button three times:
Let me know if you have any suggestions that I can try.
Thank you for your time,

I was able to update my text window instead of create a new one, upon each click of a button, thanks to #TheLizzard.
He mentioned to move the section of code that creates the text window outside of the function and keep the section of code that creates the text, inside the function.
Before:
#button initiators
def buttonupdate():
S = Scrollbar(homepage)
T = Text(homepage, height=100, width=30)
T.pack()
T.pack(side=RIGHT, fill= Y)
S.pack(side = RIGHT, fill = Y)
S.config(command=T.yview)
T.insert(END, "test")
T.config(yscrollcommand=S.set, state=DISABLED)
After: (UPDATED)
S = Scrollbar(homepage)
T = Text(homepage, height=100, width=30)
T.pack(side=RIGHT, fill= Y)
S.pack(side = RIGHT, fill = Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set, state=DISABLED)
#button initatiors
def myTicketstatusbutton():
T.delete(1.0,END)
T.insert(END, "test")

Related

How do I make a tkinter button destroy itself?

I made this program in Tkinter in python where a small window pops up when the code is run and a start button would pop up and make the window full screen and show the content after. I want to make the button destroy itself after I press it so it makes a fullscreen and removes the button. I am still a beginner and would like the answer to be simple. The solution I am looking for is to maybe destroy the button completely(preferred) or move it way out of sight in the fullscreen window. Here is the code:
import Tkinter as w
from Tkinter import *
w = Tk()
w.geometry("150x50+680+350")
def w1():
w.attributes("-fullscreen", True)
l1 = Label(w, text = "Loaded!", height = 6, width = 8).pack()
global b1
b1.place(x = -10000, y = -10000)
b1 = Button(w, text = "Start", height = 3, width = 20, command = w1).place(x = 0, y = 10)
b2 = Button(w, text = "Exit", command = w.destroy).place(x = 1506, y = 0)
w.mainloop()
As you can see I want to make button one destroy itself.
Try this:
import tkinter as tk # Use `import Tkinter as tk` for Python 2
root = tk.Tk()
root.geometry("150x50+680+350")
def function():
global button_start
root.attributes("-fullscreen", True)
label = tk.Label(root, text="Loaded!", height=6, width=8)
label.pack()
button_start.place_forget() # You can also use `button_start.destroy()`
button_start = tk.Button(root, text="Start", height=3, width=20, command=function)
button_start.place(x = 0, y = 10)
button_exit = tk.Button(root, text="Exit", command=root.destroy)
button_exit.place(x=1506, y=0)
root.mainloop()
PS: Please read this.
Try:
b1.place_forget()
This will essentially "forget" about the button and hide it from view.
Edit:
If you are getting the error that b1 is None try:
b1 = Button(w, text = "Start", height = 3, width = 20, command = w1)
b1.place(x = 0, y = 10)
You need to add the b1.place() option at the bottom for this to work

Deleting focused entry widget on button click

I added a feature to my program where upon adding an image, the path of the image will be displayed in an entry widget. Now I would like to add the possibility to delete these path entries. When clicking on an entry, it should take focus. A button click should then delete the entry currently in focus. The below code seems to fail at the 'Entry Widget Focus' part as the focus always stays on the 'txtImage1' entry. Any help is greatly appreciated.
#Variables
Image1 = StringVar()
Image2 = StringVar()
Image3 = StringVar()
Image4 = StringVar()
#Image Path Entry Widgets
lblImage1 = Label(PictureFrame2, font=('Arial',12), text="Image 1", bg="#d9e1f1")
lblImage1.grid(row=2,column=0)
txtImage1 = Entry(PictureFrame2, font=('Arial',12), textvariable=Image1, bg="ghost white", width = 10)
txtImage1.grid(row=3,column=0)
lblImage2 = Label(PictureFrame2, font=('Arial',12), text="Image 2", bg="#d9e1f1")
lblImage2.grid(row=2,column=1)
txtImage2 = Entry(PictureFrame2, font=('Arial',12), textvariable=Image2, bg="ghost white", width = 10)
txtImage2.grid(row=3,column=1)
lblImage3 = Label(PictureFrame2, font=('Arial',12), text="Image 3", bg="#d9e1f1")
lblImage3.grid(row=2,column=2)
txtImage3 = Entry(PictureFrame2, font=('Arial',12), textvariable=Image3, bg="ghost white", width = 10)
txtImage3.grid(row=3,column=2)
lblImage4 = Label(PictureFrame2, font=('Arial',12), text="Image 4", bg="#d9e1f1")
lblImage4.grid(row=2,column=3)
txtImage4 = Entry(PictureFrame2, font=('Arial',12), textvariable=Image4, bg="ghost white", width = 10)
txtImage4.grid(row=3,column=3)
#Entry Widget Focus
def image1click(event):
txtImage1.focus_set()
txtImage1.bind("<Button-1>", image1click)
def image2click(event):
txtImage2.focus_set()
txtImage2.bind("<Button-1>", image2click)
def image3click(event):
txtImage3.focus_set()
txtImage3.bind("<Button-1>", image3click)
def image4click(event):
txtImage4.focus_set()
txtImage4.bind("<Button-1>", image4click)
#Delete Image on Focus
def Deleteimage():
messageDelete= tkinter.messagebox.askyesno ("","Do you want to delete this image?")
if messageDelete > 0:
try:
if txtImage1.focus_get():
Image1.set("")
else:
if txtImage2.focus_get():
Image2.set("")
else:
if txtImage3.focus_get():
Image3.set("")
else:
if txtImage4.focus_get():
Image4.set("")
except Exception:
pass
#Delete Button
btnDeleteImage = Button(PictureFrame, text='Delete', font=('arial',12), height=1, width=12, bd=2, padx=13, command=Deleteimage)
btnDeleteImage.grid(row=1,column=1)
focus_get() doesn't return a boolean, it returns the actual widget that has focus. txtImage1.focus_get(), txtImage2.focus_get(), etc all will return the same thing: the widget that has focus.
You can replace that whole if/else chain with this (and you can use any widget in place of txtImage1):
widget = txtImage1.focus_get()
widget.delete(0, "end")
Also, there's no need to call a function on a button click to set the focus, that happens automatically.

Refresh my tkinter label and lets it overwrite it with different output content

I have a Submit button that prints the output on the tkinter widget label. Everytime I change the input and click the Submit the output is displayed but not at the same place i.e. The previous content of the label is not overwritten.
from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("ImageValidation ")
root.geometry("600x600+100+100")
pathlist = [None, None] # holds the two files selected
labels = []
def browse_button(index):
global filename
filename = filedialog.askopenfilename(title = "Choose your file",filetypes = (("jpeg files","*.jpeg"),("all files","*.*")))
pathlist[index] = filename
heading = Label(root, text = "Select 2 images you want to Validate",
font=("arial",15,"bold","underline"), fg="blue").pack()
label1 = Label(root, text = "Enter Image 1", font=("arial",10,"bold"),
fg="black").place(x=10, y = 100)
label2 = Label(root, text = "Enter Image 2", font=("arial",10,"bold"),
fg="black").place(x=10, y = 200)
button = Button(root,text="Choose an Sign1",width = 30,command= lambda:
browse_button(0)).place(x=250, y= 100)
button = Button(root,text="Choose an Sign2",width = 30,command=
lambda: browse_button(1)).place(x=250, y= 200)
def display():
ImageVerification(pathlist[0], pathlist[1])
l1 = Label(root,text=Scriptoutput, width = 200 )
l1.pack(side='bottom', padx=50, pady=50)
#Scriptoutput is the output variable from the main code.
submit_button = Button(text="Submit", width=15,command = display)
submit_button.pack(side='bottom', padx=15, pady=15)
root.mainloop()
A 'refresh' button that would clear the Label of its content and lets you overwrite it.
I am taking your function ImageVerification() as a blackbox and assuming it is working.
The reason this is happening is because you create a new Label, whenever the Submit button is pressed. What you have to do is to create the display Label outside the function and configure its text, whenever the button is pressed. Something like this.
l1 = Label(root, text="", width=200)
l1.pack(side='bottom', padx=50, pady=50)
def display():
ImageVerification(pathlist[0], pathlist[1])
l1.configure(text=Scriptoutput)
#Scriptoutput is the output variable from the main code.
submit_button = Button(text="Submit", width=15,command = display)
submit_button.pack(side='bottom', padx=15, pady=15)

Switch between multiple frames using tkinter in python in side menubar

I am trying to create a side menubar and use multiple labels as click buttons. But when I execute the program, only one label is clicked and event is shown in mainarea. Other event doesn't work.
Please provide me with a useful solution. Here is the code I have written:
from Tkinter import *
import ttk
root = Tk()
def MainScreen(self):
label4 = Label(mainarea,width=100,height=80,text="Prapti Computer
Solutions")
label4.pack(expand=True,fill='both')
def ClientData(self):
label4 = Label(mainarea,width=100,height=80,text="Yo this is client data")
label4.pack(expand=True,fill='both')
def Report(self):
label6 = Label(mainarea,width=100,height=80,text="Report is onnnnn!")
label6.pack(expand=True,fill='both')
# sidebar
sidebar = Frame(root, width=400, bg='white', height=500, borderwidth=2)
sidebar.pack( fill='y', side='left', anchor='nw')
#submenus
label1 = Label( sidebar,width=45,height = 2 , text="HOME", relief=FLAT )
label1.bind("<Button-1>",MainScreen)
label1.grid(row=0)
ttk.Separator(sidebar,orient=HORIZONTAL).grid(row=1, columnspan=5)
label2 = Label( sidebar,width=45,height = 2 , text="CLIENT", relief=FLAT )
label2.bind("<Button-1>",ClientData)
label2.grid(row=2)
ttk.Separator(sidebar,orient=HORIZONTAL).grid(row=3, columnspan=5)
label3 = Label( sidebar,width=45,height = 2 , text="REPORT", relief=FLAT )
label3.bind("<Button-1>",Report)
label3.grid(row=4)
# main content area
mainarea = Frame(root, bg='#CCC', width=500, height=500)
mainarea.pack(expand=True, fill='both', side='right')
root.attributes('-alpha', 0.98)
root.mainloop()
Thank you.
You keep packing things but you never remove them. You need to remove the current page before switching to the new page.
For example:
current_page = None
def MainScreen(self):
global current_page
if current_page is not None:
current_page.pack_forget()
label4 = Label(mainarea,width=100,height=80,text="Prapti Computer Solutions")
label4.pack(expand=True,fill='both')
current_page = label4

Unable to achieve wanted entry textBox alignment

HI i am trying to place the alignment of my Entry(Text Box) according to the image below. I tried everything, TOP BOTTOM LEFT RIGHT.
This is the alignment i want. Obtained from paint program*
Problem
Coding of tkinter
master = Tk.Tk() # Open up GUI connection
master.title('Program Application')
print "VSM activated input range first (X2 must be larger than X1)"
#Declare button and respective method
button = Tk.Button(text='VSM', command=VSM, fg="red")
button.config( height = 10, width = 80 )
button.pack() #pack is needed to display the button
bluebutton = Tk.Button(text="AGM Folder",command= lambda: Folder(0), fg="blue").pack(side = LEFT)
bluebutton = Tk.Button(text="VSM Folder",command= lambda: Folder(1), fg="blue").pack(side = RIGHT)
Label(text='Correct Range for Gradient\nX2 X1').pack(side=TOP,padx=10,pady=10)
entryX2 = Entry(master, width=10)
entryX2.pack(side=LEFT,padx=10,pady=10)
entryX1 = Entry(master,width=10)
entryX1.pack(side=RIGHT,padx=10,pady=10)
buttonGradient = Tk.Button(text='Input Range OP',command= lambda: Folder(2), fg="red").pack()
entryX2IP = Entry(master, width=10)
entryX2IP.pack(side=LEFT,padx=10,pady=10)
entryX1IP = Entry(master,width=10)
entryX1IP.pack(side=RIGHT,padx=10,pady=10)
btnGradientIP = Tk.Button(text='Input Range IP',command= lambda: Folder(2), fg="red").pack(side = TOP)
master.mainloop() # Continue loop till user close tab
Use Frame:
master = Tk.Tk() # Open up GUI connection
master.title('Program Application')
print "VSM activated input range first (X2 must be larger than X1)"
#Declare button and respective method
button = Tk.Button(text='VSM', command=VSM, fg="red")
button.config( height = 10, width = 80 )
button.pack() #pack is needed to display the button
bluebutton = Tk.Button(text="AGM Folder",command= lambda: Folder(0), fg="blue").pack(side = LEFT)
bluebutton = Tk.Button(text="VSM Folder",command= lambda: Folder(1), fg="blue").pack(side = RIGHT)
Label(text='Correct Range for Gradient\nX2 X1').pack(side=TOP,padx=10,pady=10)
################### Use 3 frames to contains entries, buttons.
frameX2 = Frame(master)
frameX2.pack(side=LEFT, expand=1, anchor=E)
entryX2 = Entry(frameX2, width=10)
entryX2.pack(side=TOP,padx=10,pady=10)
entryX2IP = Entry(frameX2, width=10)
entryX2IP.pack(side=TOP,padx=10,pady=10)
frameButton = Frame(master)
frameButton.pack(side=LEFT)
Tk.Button(frameButton, text='Input Range OP',command= lambda: Folder(2), fg="red").pack(padx=10, pady=10)
Tk.Button(frameButton, text='Input Range IP',command= lambda: Folder(2), fg="red").pack(padx=10, pady=10)
frameX1 = Frame(master)
frameX1.pack(side=LEFT, expand=1, anchor=W)
entryX1 = Entry(frameX1,width=10)
entryX1.pack(side=TOP,padx=10,pady=10)
entryX1IP = Entry(frameX1,width=10)
entryX1IP.pack(side=TOP,padx=10,pady=10)
#####################
master.mainloop() # Continue loop till user close tab

Categories