Code Part 1
from tkinter import *
from PIL import Image, ImageTk
import threading
c1 = "#262626"
root = Tk()
root.overrideredirect(True)
root.configure(bg=c1)
def destroy():
global root
root.destroy()
def pr():
print("asd")
destroy()
def animation():
threading.Timer(0.01, pr).start()
animation()
root.mainloop()
after the destroy () command has worked, the window is closed, but the program continues to work, you can disable it only with the help of the task manager or CMD, but there's no any errors.
Code Part 2
login = Tk()
img = Image.open(selfDir + "\\ok.png").resize((50, 50), Image.ANTIALIAS)
test = ImageTk.PhotoImage(img)
label1 = Label(login, image=test, bg=c1)
label1.image = test
label1.place(x=330, y=145, width=50, height=50)
login.mainloop()
if I run this part after the first one, I see an error:
tkinter.TclError: can't invoke "image" command: application has been destroyed
but if I run only this part, without the first one, then it works and I can see the photo in the window
So the problem is.
I need to close window after threading.Timer()
Then i need to open window, with an image
i just need to write
root.after(10, pr)
instead of
threading.Timer(0.01, pr).start()
special thanks to Matiiss
Related
I'm trying to show and hide a png (With no frame, margin, or title bar) but can't find a good way to do it. I tried using matplotlib but the code has to be in the main thread so I can't figure out how to use functions to show or hide it. I also tried tkinter but ran into the same problem where calling it from a function the code would just stop when trying to call it from a function.
Is there a simple way to accomplish this?
Below is what I am trying to accomplish though the code doesn't display any image. The code doesn't return an error either, it just stops executing at mainloop without displaying anything unless the code is in the main thread.
#Import modules
import os #For working directory
from pynput import keyboard #For hotkeys
from tkinter import *
from PIL import ImageTk,Image
#Set default directory
os.chdir('C:\\Users\\Username\\Desktop\\Python')
#Define global variables
global img
#Functions
def ExitProgram():
print('test')
#sys.exit(0)
quit() #Will not work in production, switch to sys.exit
return
def ShowImage():
root = Tk()
canvas = Canvas(root, width=300, height=300)
canvas.pack()
img = ImageTk.PhotoImage(Image.open("menu.png"))
canvas.create_image(20, 20, anchor=NW, image=img)
root.overrideredirect(True) # removes title bar
root.mainloop()
print('test')
return
#Define hotkeys
with keyboard.GlobalHotKeys({
'<ctrl>+q': ExitProgram,
'<ctrl>+0': ShowImage}) as h:
h.join()
I have been searching for a solution for this issue, but I can't seem to find a viable answer.
I have the following code to open another tkinter script on button click:
# Program to Open on Button Click
def tkinter1():
ret = os.system('python C:\filepath\new_script.py"')
if ret:
# record updated, reload data
treeview_preview()
b1 = Button(master, text="New Window", command=tkinter1)
My problem I am facing is that I want the current window to close on the button click and only keep the new window open.
I know it is possible. I have this instance with many different windows and I seem to be stuck.
The unfortunate thing is that I have an entire different script for different parts of the beta software and the only way I could successfully run all of them is to access them as stated above.
I tried using the if ret: exit() command at the end with the same result. I have windows opening over and over again.
It seems simple, but I haven't been programming tkinter script for too long.(I still have a lot to learn)
All help is appreciated.
You can use master.withdraw(). I
made your code runnable with a few lines. Ok lets say your fixed main code is this:
import tkinter as tk
from tkinter import *
from seccond import *
from multiprocessing import Process
import os
def main():
master = tk.Tk()
# Program to Open on Button Click
def tkinter1():
master.withdraw()
master.destroy()
ret = Process(target=treeview_preview())
ret.start()
#if ret:
# # record updated, reload data
# treeview_preview()
#commented out bc i don't know what it is
b1 = Button(master, text="New Window", command=tkinter1)
b1.pack()
master.mainloop()
if __name__ == '__main__':
main()
the secondary code name seccond.py in the same folder as the main code is called as an external function but also as a separate process.
import tkinter as tk
def treeview_preview():
root = tk.Tk()
S = tk.Scrollbar(root)
T = tk.Text(root, height=4, width=50)
S.pack(side=tk.RIGHT, fill=tk.Y)
T.pack(side=tk.LEFT, fill=tk.Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
quote = """this is the seccond window."""
T.insert(tk.END, quote)
tk.mainloop()
The code will remove the window but not the terminal box as it will use it for the second script.
I'm trying to create a python program tkinter that, upon the pressing of a button, opens a new full screen tkinter window containing an image and plays an audio file - here's my code:
from tkinter import *
from PIL import Image, ImageTk
from playsound import playsound
def play():
window = Toplevel()
window.attributes('-fullscreen', True)
img = ImageTk.PhotoImage(Image.open("pic.png"))
label = Label(window, image=img).pack()
playsound("song.mp3")
buttonWindow = Tk()
b = Button(buttonWindow, text="Press Button", command=play)
b.pack()
(my image and audio file are both on the desktop with my python file)
However, when I run my code, when I press the button, the audio plays but no second tkinter window opens.
I've tried to destroy() the buttonWindow and have tried many different ways of including an image on a tkinter window - if I remove the line of code using PhotoImage(), the window appears (obviously I then get a syntax error stating that 'img' is not defined).
How could I solve this?
Thanks,
Louis
I had similar problem.
But i resolve this trial and error method.
First of all i don't use pillow library and put image into Label
You should try define Photoimage object NOT IN FUNCTION
Example:
It will work:
import tkinter as tk
root = tk.Tk()
root.geometry("600x400")
def popUp():
popff = tk.Toplevel(root)
popff.geometry("400x200")
labelImgff = tk.Label(popff, image=imgff, bg="white")
labelImgff.grid(row=0, column=0)
imgff = tk.PhotoImage(file="/home/user/image.png")
btnff = tk.Button(text="startPOP", command=popUp)
btnff.grid(column=0,row=0)
root.mainloop()
effect of action
Your playsound() command is blocking execution. The playsound() command has an optional field 'block', which is True by default. Changing this to False will continue execution and allow mainloop() to continue.
Second, just call label.draw() to draw your image to the TopLevel window.
Here's the code:
from tkinter import *
from PIL import Image, ImageTk
from playsound import playsound
def play():
window = Toplevel()
window.attributes('-fullscreen', True)
img = ImageTk.PhotoImage(Image.open("pic.jpeg"))
label = Label(window, image=img).pack()
playsound("song.mp3",block=False)
label.draw()
buttonWindow = Tk()
b = Button(buttonWindow, text="Press Button", command=play)
b.pack()
buttonWindow.mainloop()
Cheers!
I am trying to open an image in fullscreen to overlap the taskbar and show no menu bar using python.
I got it to work using Tkinter with following code, but since its just a single image that does not need to be updated (ever), the blocking loop of mainloop() is very inconvenient and unnecessary. However, I can't get tkinter to stay open without that update loop. I've tried using root.after() to run the function afterwards but that froze my program (and isn't really what I want to do anyway)
root = tk.Tk()
root.update_idletasks()
root.attributes('-fullscreen', True)
root.overrideredirect(1)
output = self.create_image_from_array(image_array)
canvas = tk.Canvas(root, width=root.winfo_width(), height=root.winfo_height())
canvas.create_image(0, 0, image=output, anchor="nw")
canvas.pack(fill=tk.BOTH, expand=1)
# after freezes my window
# root.after(0,someFunction)
# main loop blocking the function.
root.mainloop()
How can I display a single image on the entire screen using python (in both windows and linux) or how can I "pause" the tkinter loop to prevent the window from closing and updating?
It looks like you will have to handle tkinter's thread yourself rather than relying on mainloop(). Here is one way to do it:
import tkinter as tk
from threading import Thread
import time
class SomeFunc:
def __init__(self):
self.running=True
t = Thread(target=self.func)
t.start()
def func(self):
self.root = tk.Tk()
self.root.update_idletasks()
#root.attributes('-fullscreen', True)
#root.overrideredirect(1)
canvas = tk.Canvas(self.root, width=self.root.winfo_width(), height=self.root.winfo_height())
#canvas.create_image(0, 0, image=output, anchor="nw")
canvas.pack(fill=tk.BOTH, expand=1)
while self.running:
self.root.update()
a = SomeFunc()
x = 10
while x:
x-=1
time.sleep(1)
print(x)
I've been experimenting a little with the Canvas function of Tkinter and tried to add some imagefile to the window, to test if i can create proper background images.The code so far seems to be working fine (atleast i get no errors when executing). But as soon as i try to execute the Python script it just takes forever to load and doesn't display a window or anything. As soon as i remove the Canvas block from my script it works fine.
from Tkinter import *
root = Tk()
root.title("ImageTest")
root.geometry("350x150")
root.minsize(350,150)
root.maxsize(350,150)
#***** Canvas *****
photo = PhotoImage(file="derp.gif")
w = Canvas(root, width=350, height=150)
w.pack()
w.create_image(0,0, anchor=NW, image=photo)
w.image = photo
root.mainloop()