My full code
from tkinter import *
i=0
for i in range(10) :
window = Tk()
window.title('add image')
window = Canvas(window,width= 600, height= 600)
window.pack()
image=PhotoImage(file=r"C:\\Users\\Konstantinos\\New folder\\hello.png")
window.create_image(0,0, anchor = NW, image=image)
window.mainloop()
The error when i run the program
File "C:\Programms\Lib\tkinter\__init__.py", line 2832, in _create
return self.tk.getint(self.tk.call(
^^^^^^^^^^^^^
_tkinter.TclError: image "pyimage2" doesn't exist
The error when i debug the program
Exception has occurred: TclError
image "pyimage2" doesn't exist
File "C:\Users\Konstantinos\New folder\demo.py", line 9, in <module>
window.create_image(0,0, anchor = NW, image=image)
So basically, the program opens an image multiple times. When th program is not in a loop it works but when i put it in a loop it gives me the error. Because i recently started programming i dont really know how to solve the problem and I have looked in other threads with the similar problem but none apply to me. I will appreciate any answer
The error probably comes from multiple Tk instances. Try removing the for-loop and then it will work. But if your intention was for multiple windows, then you can look into this answer: https://stackoverflow.com/a/36316105/9983213. Feel free to tinker around with the example.
A smaller example is:
import tkinter as tk
root = tk.Tk()
for i in range(5):
top = tk.Toplevel(root)
root.mainloop()
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()
import tkinter as tk
from tkinter import ttk,font
from PIL import Image,ImageDraw,ImageFont
root = tk.Tk()
def func_image():
image = Image.open(r'E:\side_300.png')
font_type_1 = ImageFont.truetype(str(combo.get()),18)
draw = ImageDraw.Draw(image)
draw.text((50,50),text='Hello',fill='red',font=font_type_1)
image.show()
fonts=list(font.families())
fonts.sort()
combo = ttk.Combobox(root,value=fonts)
combo.pack()
btn = ttk.Button(root,text='Click Me',command=func_image)
btn.pack()
root.mainloop()
Output
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Mevada\AppData\Local\Programs\Python\Python37\lib\tkinter__init__.py", line 1702, in __call__return self.func(*args)
File "test.py", line 9, in func_image
font_type_1 = ImageFont.truetype(str(combo.get()),18)
File "C:\Users\Mevada\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 280, in truetype return FreeTypeFont(font, size, index, encoding, layout_engine)
File "C:\Users\Mevada\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 145, in __init__layout_engine=layout_engine)
OSError: cannot open resource
Thanks...
import tkinter as tk
from tkinter import ttk
from PIL import Image,ImageDraw,ImageFont
import matplotlib.font_manager as fm
root = tk.Tk()
def func_image():
image = Image.open(r'E:\side_300.png')
font_type_1 = ImageFont.truetype(fm.findfont(fm.FontProperties(family=combo.get())),18)
draw = ImageDraw.Draw(image)
draw.text((50,50),text='Hello',fill='red',font=font_type_1)
image.show()
fonts = list(set([f.name for f in fm.fontManager.ttflist]))
fonts.sort()
combo = ttk.Combobox(root,value=fonts)
combo.pack()
btn = ttk.Button(root,text='Click Me',command=func_image)
btn.pack()
root.mainloop()
ImageFont.truetype requires that you give it a filename. You're not giving it a filename, you're giving it the name of a font family. Tkinter's font.families() does not return filenames.
It seems font cannot be found by PIL.
Find your font file in your computer. In windows, it always in C:\WINDOWS\Fonts directory. select one and modify your line 9 like it:
font_type_1 = ImageFont.truetype("bahnschrift.ttf",18)
bahnschrift.ttf is just a sample on my computer, I am not sure it exists on your computer.
It does not work because you have to insert the font filename as the first argument here: ImageFont.truetype(str(combo.get()),18).
If you try, for example, arial, you will succeed (if you have Arial installed on your computer, of course). Oh, and that function is case sensitive, so you have to write it in lowercase, because the filename is actually arial.ttf (you can drop the extension if want, by the way).
So, your combo box isn't working because when you choose a font named Courier New, for example, PIL won't find it, because its filename is cour.ttf. Unfortunately, you can't use that list of fonts from tkinter on ImageFont and I don't have a workaround for you in that case.
As I said, this might work, but you have to let go of your combo box: ImageFont.truetype('arial',18)
Before I go, one more important note: if you are working on a OS other than Windows, you have to type the full path to the font file.
I'm currently trying to create a Python3 Tkinter program which I can launch by double clicking or opening from other python scripts, instead of going through idle.
So far I've had little luck, as when I attempt to launch the script the console opens for a moment and then crashes.
EDIT: Removing the logo segment of code allows the program to run. Any ideas why and how to fix it? Also I have not had to run a program via the console before so little luck there.
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("Kinematics")
Logo_frame = LabelFrame(root, bg = "white")
Logo_frame.grid(row=0, column=12, sticky = "NSEW")
#Logo
Logo = Image(file="Logo-S.gif")
image_label = ttk.Label(Logo_frame, image=Logo)
image_label.grid(row=0, column=0, rowspan = 3)
root.mainloop()
The error from your present code is:
Exception ignored in: <bound method Image.__del__ of <tkinter.Image object at 0x7f1aa91df2e8>>
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 3357, in __del__
if self.name:
AttributeError: 'Image' object has no attribute 'name'
Traceback (most recent call last):
File "/home/sunbear/Coding/python35/tkinter/stackoverflow_questions/test52.py", line 22, in <module>
Logo = Image(file="Logo-S.gif")
TypeError: __init__() missing 1 required positional argument: 'imgtype'
There is a typo in your command in line 22(your original code before edit). You need the following correction to overcome this error, i.e.:
#Logo
#Logo = Image(file="Logo-S.gif")
Logo = PhotoImage(file="Logo-S.gif") #you should change to this.
You can read more about when to use PhotoImage and Image using this link I gave you.
I just attempted to run the program with a random gif I found online, all seemed to work to plan. I'm running windows 10 pro... maybe try re-saving/downloading the gif.
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()
I am getting the error "Global name 'start' is not defined" from the code snippet below. But the start(panel) call in displayImage(img) causes the image I want to see to be displayed in the GUI; without it no image shows up; it must be doing something. Yet I get the above error. I'm running this program in Ubuntu 12.04. BTW, I am new to both Python and Tkinter. Any way to get rid of this error? Edit: The adding of the image occurs during runtime with a button click that calls loadPicture(file).
import numpy as np
from Tkinter import *
import cv2 as cv
from tkFileDialog import askopenfilename
import tkSimpleDialog as td
import math as mt
from PIL import ImageTk, Image
### General functions #############################################
def raiseFileChooser():
global filename
filename = askopenfilename()
loadPicture(filename)
def loadPicture(file):
# set global variable for other uses
global img
img = cv.imread(file, 1)
img = cv.cvtColor(img, cv.COLOR_RGB2BGR)
displayImage(img, display1)
def displayImage(image, panel):
temp = Image.fromarray(image)
bk = ImageTk.PhotoImage(temp)
bkLabel = Label(display1, image = bk)
bkLabel.place(x=0, y=0, relwidth=1, relheight=1)
start(panel)
### Start App ###########################################
#### get GUI started
root = Tk()
np.set_printoptions(threshold=np.nan) # so I can print entire arrays
### global variables ####################################
relStatus = StringVar()
relStatus.set(None)
text = StringVar()
filepath = StringVar()
filename = "No file chosen"
img = None
gsc = None
eStatus = StringVar()
eStatus.set(None)
display1 = None
display2 = None
### GUI #################################################
root.title("Picture Transformer")
root.geometry("700x600")
app = PanedWindow(root)
app.pack(padx=20, pady=20)
#Button Panel##############
buttonPanel = Frame(app,width=200, height = 400)
buttonPanel.pack(side=LEFT)
chooser = Button(buttonPanel, text="Choose File", height=1, width=9, command=raiseFileChooser)
chooser.pack()
#set up display panels ###########################
display1 = Frame(app, width=900, height=900, bg="#cccccc")
display1.pack(side=LEFT, fill=BOTH, expand=1)
root.mainloop()
Edit:
Stacktrace:
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
return self.func(*args)
File "hw2.py", line 78, in raiseFileChooser
loadPicture(filename)
File "hw2.py", line 86, in loadPicture
start(panel)
NameError: global name 'start' is not defined
The error is telling you exactly what's wrong -- there is no global start function in your code. In fact, as near as I can tell, there's no start method anywhere, in any object that you are creating. Why do you think you should be calling a function named start? Is there some documentation somewhere that is telling you to do this?
My guess is, you're running in IDLE, and when you call the non-existent start function, the script crashes. When the script crashes it returns to IDLE, and whatever windows you had created to that point are now visible.
The most obvious problem you have in your code is that you aren't creating a root window. Somewhere early in your script, before you create any widgets or instances of StringVar you need to do something like this:
root = Tk()
root.mainloop() in the place of start() works.
Try
panel.start()
Just a guess.Give a try, you might be able to solve the problem.