tkinter window works well only in the first execution - python

I've been trying to build a tkinter window that has some Check buttons, an image, and a button. I use the Spyder IDE and the code works just fine when I open Spyder and run it for the first time. But when I try to execute again, the image doesn't appear, and also apparently the window does not get destroyed by the button I've created. Is there something wrong with my code?
Here is my code:
import tkinter as tk # GUI configuration
from PIL import ImageTk, Image
# Window to select the analysis actions
config_window = tk.Tk()
config = { # Dictionary with variables that control what the algorithm will do
"EDIT_FILES": tk.BooleanVar(),
"RMS_ANALYSE": tk.BooleanVar(),
"WATERFALL_FFT": tk.BooleanVar()
}
config_window.title('Analysis settings')
label = tk.Label(config_window, text='Please check the boxes corresponding to the operations you would like to do',\
background='red')
label.grid(row=0, sticky='n')
tk.Checkbutton(config_window, text='Edit the files created from the sensor measurements', \
variable=config["EDIT_FILES"]).grid(row=1, sticky='w')
tk.Checkbutton(config_window, text='RMS analysis', \
variable=config["RMS_ANALYSE"]).grid(row=2, sticky='w')
tk.Checkbutton(config_window, text='FFT analysis', \
variable=config["WATERFALL_FFT"]).grid(row=3, sticky='w')
image = Image.open("logo.png").resize((220,80), Image.ANTIALIAS)
logo = ImageTk.PhotoImage(image, size=10)
im_label = tk.Label(image=logo)
im_label.image = logo
im_label.grid(row=4, sticky='w')
tk.Button(config_window, text='Ok', width=10, command=config_window.destroy).grid(row=4, sticky='e')
config_window.mainloop()

Related

How To Put Widgets In A New Tkinter Window?

I wanted to add widgets to a new tkinter window, so I tried this:
old_window = Tk()
new_window = Tk()
old_window.destroy()
new_window.geometry("750x550")
image = Label(new_window, image = dernier).pack
button1 = Button(new_window, text = "Oui", font= ("", 25), command = button1_press).place(x=250, y=475)
button2 = Button(new_window, text = "Non", font= ("", 25), command = button2_press).place(x=425, y=475)
But, just a basic window pops out, with nothing inside.
Python version: 3.9.7
Integrated Development Environnement (Also known as IDE): Visual Studio Code.
The tk.Tk() class isn't just a window, it's also what controls the entire application and has an associated Tcl interpreter. Creating multiple of these, and destroying them part way through an application, can cause many problems. Instead, for creating a new window, use the tk.Toplevel() class.
For example:
import tkinter as tk
root = tk.Tk()
a = tk.Toplevel()
b1 = tk.Button(a, text="new toplevel", command=lambda: tk.Toplevel())
root.mainloop()

Why does my button not display in GUI (Python,TK)

I am trying to create a simple GUI in Python to create buttons to access apps within my computer.
I am very new to Python & coding in general so bear with me..
I am getting 0 error messages when running the code but it just isn't displaying the button at the bottom. Here's what I have written out.
Here's a screenshot of my result
import tkinter as tk
from tkinter import filedialog, Text
import os
root = tk.Tk()
canvas = tk.Canvas(root, height=700, width=700, bg="#263D42")
canvas.pack()
frame = tk.Frame(root, bg="white")
frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)
openFile = tk.Button(root, text="Open File", padx=10,
pady=5, fg="white", bg="#263D42")
openFile.pack()
root.mainloop()

Tkinter Toplevel inf different file/function

I am trying to create a Toplevel window, however, this Toplevel is called from a different file in the same directory within a function.
Apologies I am by no means a tkinter or python guru. Here are the two parts of the code. (snippets)
#File 1 (Main)
import tkinter as tk
from tkinter import *
import comm1
from comm1 import com1
root = tk.Tk()
root.title("")
root.geometry("1900x1314")
#grid Center && 3x6 configuration for correct gui layout
root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(11, weight=1)
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(11, weight=1)
#background image
canvas = Canvas(root, width=1900, height=1314)
canvas.place(x=0, y=0, relwidth=1, relheight=1)
bckground = PhotoImage(file='img.png')
canvas.create_image(20 ,20 ,anchor=NW, image=bckground)
#command to create new Toplevel
btn1 = tk.Button(root, text='Top', command=com1, justify='center', font=("Arial", 10))
btn1.config(anchor=CENTER)
btn1.grid(row=4, column=1)
#File 2 (Toplevel)
#command for new window
def com1():
newWindow1 = Toplevel(root)
newWindow1.title("")
newWindow1.geometry("500x500")
entry1 = tk.Entry(root, justify='center' , font=("Arial", 12), fg="Grey")
newWindow1.pack()
newWindow1.mainloop()
The weird part is this worked perfectly for a few minutes and without changing any code it just stopped working.
Where am I going wrong?
You need to pass root as an argument to com1
Also, you only need to start mainloop once, and that should probably be in the main file. You do not need to call it each time you create a new window.
Thanks everyone that answered,
Decided to bypass the problem with better structuring in a single file. :)

Tkinter paste image in textbox from clipboard

I am trying to paste get an image from clipboard and paste it into the textbox/label in tkinter. My code is below.
# page4 buttons and functions
f7 = Frame(page4)
f7.grid(row=0, column=0, sticky='NESW')
f8 = Frame(page4)
f8.grid(row=0, column=0, columnspan=2, sticky='NESW')
tb8 = Label(f7, width=82)
tb8.grid(row=0, column=0, sticky='NESW')
tb9 = Text(f7, width=30)
tb9.grid(row=0, column=1, sticky='NESW')
def imgps():
try:
image = root.selection_get(selection='CLIPBOARD')
img = ImageTk.PhotoImage(Image.open(image))
tb8.config(page4, image=img)
tb8.clipboard_clear()
except:
messagebox.showinfo(message="Clipboard is Empty.")
pbtn11 = Button(f8, text="IMAGE", activebackground="lavender",
activeforeground="RoyalBlue", bd="5", bg="aquamarine2",
command=imgps, fg="purple", font=('arial', 10, 'bold'))
pbtn11.grid(row=0, column=0, sticky='NESW')
Nothing appears on the area intended and neither any error is shown up. But, whence I close the application. the Messagebox turns up. Seems like weird coding. Can somebody help.
Here is a simple example of adding an image to the label.
Keep in mind you will need to make sure that a reference to the image is saved or else you will not see an image in your app.
Update:
I believe this updated answer should work for you. The code will try to grab the image from clipboard using the ImageGrab method in PIL if there is one and then it saves the image to a temp folder. We then load that image to the label and then delete the image from the temp folder.
import tkinter as tk
import os
from tkinter import messagebox
from PIL import ImageTk, ImageGrab
root = tk.Tk()
tb8 = tk.Label(root, width=82)
tb8.grid(row=0, column=0, sticky='nsew')
def imgps():
try:
temp_path = "./TempImage/some_image.gif" # Whatever temp path you want here
im = ImageGrab.grabclipboard() # Get image from clipboard
im.save(temp_path) # save image to temp folder
load_for_label = ImageTk.PhotoImage(file=temp_path) # load image from temp folder
tb8.config(image=load_for_label) # set image to label
tb8.image = load_for_label # save reference to image in memory
tb8.clipboard_clear() # clear clipboard
os.remove(temp_path) # delete temp file
except:
messagebox.showinfo(message="Clipboard is Empty.")
pbtn11 = tk.Button(root, text="IMAGE", command=imgps)
pbtn11.grid(row=1, column=0, sticky='nsew')
root.mainloop()
I did try several ways to load the image directly from the clipboard but I kept running into errors. So my above solutions might not be 100% the fastest way to implement this but should work well enough.

python tkinter clicking on button to open new window

I've made 3 buttons on my window. I choosed that the main window should have a specific background image and a full screen.
Now there is a problem. I would like to move to a new window (page) (with an other background and other things) by clicking on button 3.
Things i tryd:
from Main.Info.travelhistry import *
I've added this to the main window to open a new python file with the code of the second screen that has to open when clicking on button 3. But I found out that if I do this both windows will open when running main window.
I added root1 = Tk() at the beginning, root1.mainloop() at the end and between them the code for the other window. But this won't work also, its opening 2 windows like above.
Those were all my attempts and i cant figure out a better way. I can but the background would stay the same. But I have to change the background for the new window to a background image i made...
Any idea what im doing wrong?
from tkinter import *
from tkinter.messagebox import showinfo
from Main.Info.travelhistry import *
def clicked1():
bericht = 'Deze functie is uitgeschakeld.'
showinfo(title='popup', message=bericht)
root = Tk()
a = root.wm_attributes('-fullscreen', 1)
#Hoofdmenu achtergrond
C = Canvas(root, bg="blue", height=250, width=300)
filename = PhotoImage(file = "test1.png")
background_label = Label(root, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()
# Geen OV-chipkaart button
b=Button(master=root, command=clicked1)
photo=PhotoImage(file="button1.png")
b.config(image=photo,width="136",height="53", background='black')
b.place(x=310, y=340)
#Buitenland button
b2=Button(master=root, command=clicked1)
photo1=PhotoImage(file="button2.png")
b2.config(image=photo1,width="136",height="53", background='black')
b2.place(x=490, y=340)
#Reis informatie
b3=Button(master=root)
photo2=PhotoImage(file="button3.png")
b3.config(image=photo2,width="136",height="53", background='black')
b3.place(x=680, y=340)
root.mainloop()
root2.mainloop()
You shouldn't call more than one Tk() window.
Instead, tkinter has another widget called Toplevel which can be used to generate a new window.
See below for an example:
from tkinter import *
root = Tk()
def command():
Toplevel(root)
button = Button(root, text="New Window", command=command)
button.pack()
root.mainloop()
This one opens new window that you can edit.
from tkinter import *
Window = Tk()
def Open():
New_Window = Tk()
#You can edit here.
New_Window.mainloop()
Btn1 = Button(text="Open", command=Open)
Bt1n.pack()
Window.mainloop()

Categories