I have a issue in tkinter for python 3. I would like to create an animating game character in python, tkinter without using PIL. I found a way to animate the character using a gif, but I do not know how to move the gif I tried to use canvas.move
here is my code:
from tkinter import *
import os
import time
root = Tk()
c = Canvas(root,width = 500,height = 500)
c.pack()
frames = [PhotoImage(file=(os.path.expanduser("~/Desktop/DaQueenIDLE.gif")),format = 'gif -index %i' % (i)) for i in range(2)]
def update(ind):
frame = frames[ind]
ind += 1
if ind >= 2:
ind = 0
label.configure(image=frame)
root.after(100, update, ind)
label = Label(root)
label.pack()
root.after(0, update, 0)
c.move(frames,0,-100)
root.update()
root.mainloop()
move is a method for Canvas, and its first argument needs to be an item on Canvas.
In your case frames is not an item on the Canvas.
Replace:
def update(ind):
#...
label.configure(image=frame)
root.after(100, update, ind)
label = Label(root)
label.pack()
with:
def update(ind):
#...
c.itemconfig(character, image=frame)
c.move(character, 1, 1)
root.after(100, update, ind)
character = c.create_image((47,47), image=frames[0])
To convert your label into an image item in Canvas and move it.
Example
Below is a complete example that downloads(you can comment download_images out after the initial run) .gif images below online:
and then moves an image while animating between the two:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def download_images():
# In order to fetch the image online
try:
import urllib.request as url
except ImportError:
import urllib as url
url.urlretrieve("https://i.stack.imgur.com/57uJJ.gif", "13.gif")
url.urlretrieve("https://i.stack.imgur.com/8LThi.gif", "8.gif")
def animate_and_move(i):
i = (i + 1) % 2
canvas.itemconfig(moving_image, image=canvas.images[i])
canvas.move(moving_image, 1, 1)
canvas.after(100, animate_and_move, i)
if __name__ == '__main__':
download_images() # comment out after initial run
root = tk.Tk()
canvas = tk.Canvas(root, height=644, width=644, bg='#ffffff')
canvas.images = list()
canvas.images.append(tk.PhotoImage(file="8.gif"))
canvas.images.append(tk.PhotoImage(file="13.gif"))
moving_image = canvas.create_image((164, 164), image=canvas.images[0])
animate_and_move(0)
canvas.pack()
root.mainloop()
Note that if:
import tkinter
tkinter.TkVersion >= 8.6
returns True then .png files are also supported without an additional library.
Related
So I'm writing some code to check VAT-IDs using a web API. Since some files have quite a large amount of API-calls it sometimes takes quite a while to complete and I want to show a progressbar so other users know that the program hasn't crashed yet. I found an example and modified it slightly so that it fits my needs. This code shows a window with a progressbar and once the for loop is finished the window closes.
import tkinter as tk
from tkinter import ttk
import time
def wrap():
MAX = 30000
root = tk.Tk()
root.geometry('{}x{}'.format(400, 100))
progress_var = tk.IntVar() #here you have ints but when calc. %'s usually floats
theLabel = tk.Label(root, text="Sample text to show")
theLabel.pack()
progressbar = ttk.Progressbar(root, variable=progress_var, maximum=MAX)
progressbar.pack(fill=tk.X, expand=1)
def loop_function():
k = 0
for k in range(MAX):
### some work to be done
progress_var.set(k)
time.sleep(0.002)
root.update()
root.destroy()
root.after(100, loop_function)
root.mainloop()
wrap()
Now I wanted to implement this into my tool:
import pandas as pd
import re
import pyvat
from tkinter import ttk
import tkinter as tk
def vatchecker(dataframe):
#initialise progressbar
root = tk.Tk()
root.geometry('{}x{}'.format(400, 100))
progress_var = tk.DoubleVar() #here you have ints but when calc. %'s usually floats
theLabel = tk.Label(root, text="Calling VAT Api")
theLabel.pack()
maxval = len(dataframe['Vat-ID'])
progressbar = ttk.Progressbar(root, variable=progress_var, maximum=maxval)
progressbar.pack(fill=tk.X, expand=1)
checked =[]
def loop_function():
for row in range(len(dataframe['Vat-ID'])):
print("Vatcheck: " + str(round(row/maxval * 100, 2)) + " %")
if pd.isna(dataframe['Vat-ID'][row]):
checked.append('No Vat Number')
else:
#check if vat id contains country code
groups = re.match(r'[A-Z][A-Z]', dataframe['Vat-ID'][row])
if groups != None:
querystring = dataframe['Vat-ID'][row][:-2]
country = dataframe['Vat-ID'][row][-2:]
#else get VAT-ID from Country ISO
else:
querystring = dataframe['Vat-ID'][row]
country = dataframe['Land-ISO2'][row]
try:
result = pyvat.check_vat_number(str(querystring), str(country))
checked.append(result.is_valid)
except:
checked.append('Query Error')
progress_var.set(row)
root.update()
root.destroy()
root.quit()
root.after(100, loop_function)
root.mainloop()
dataframe['Vat-ID-check'] = checked
return dataframe
This function gets called by the main script. Here the progressbar window is shown yet the bar doesn't fill up.
With print("Vatcheck: " + str(round(row/maxval * 100, 2)) + " %") I can still track the progress but it's slightly ugly.
Earlier in the main script the user already interacts with a Tkinter GUI but afterwards I close those windows and loops with root.destroy()' and 'root.quit() so I think it should be fine to run another Tkinter instance like this?
Any help or hints would be greatly appreciated.
as #jasonharper mentioned above changing progress_var = tk.DoubleVar() to progress_var = tk.DoubleVar(root) works
I am wanting to create a virtual pet style game using python3 and tkinter. So far I have the main window and have started putting labels in, but the issue I am having is playing an animated gif. I have searched on here and have found some answers, but they keep throwing errors. The result I found has the index position of the gif using PhotoImage continue through a certain range.
# Loop through the index of the animated gif
frame2 = [PhotoImage(file='images/ball-1.gif', format = 'gif -index %i' %i) for i in range(100)]
def update(ind):
frame = frame2[ind]
ind += 1
img.configure(image=frame)
ms.after(100, update, ind)
img = Label(ms)
img.place(x=250, y=250, anchor="center")
ms.after(0, update, 0)
ms.mainloop()
When I run this in terminal with "pyhton3 main.py" I get the following error:
_tkinter.TclError: no image data for this index
What am I overlooking or completely leaving out?
Here is the link to the GitHub repository to see the full project:VirtPet_Python
Thanks in advance!
The error means that you tried to load 100 frames, but the gif has less than that.
Animated gifs in tkinter are notoriously bad. I wrote this code an age ago that you can steal from, but will get laggy with anything but small gifs:
import tkinter as tk
from PIL import Image, ImageTk
from itertools import count
class ImageLabel(tk.Label):
"""a label that displays images, and plays them if they are gifs"""
def load(self, im):
if isinstance(im, str):
im = Image.open(im)
self.loc = 0
self.frames = []
try:
for i in count(1):
self.frames.append(ImageTk.PhotoImage(im.copy()))
im.seek(i)
except EOFError:
pass
try:
self.delay = im.info['duration']
except:
self.delay = 100
if len(self.frames) == 1:
self.config(image=self.frames[0])
else:
self.next_frame()
def unload(self):
self.config(image="")
self.frames = None
def next_frame(self):
if self.frames:
self.loc += 1
self.loc %= len(self.frames)
self.config(image=self.frames[self.loc])
self.after(self.delay, self.next_frame)
root = tk.Tk()
lbl = ImageLabel(root)
lbl.pack()
lbl.load('ball-1.gif')
root.mainloop()
First of all, you need to know what is the last range of your GIF file. so by changing the different value of i, you will get it.For my condition is 31.
then just need to put the condition.So it will play gif infinitely.
from tkinter import *
import time
import os
root = Tk()
frames = [PhotoImage(file='./images/play.gif',format = 'gif -index %i' %(i)) for i in range(31)]
def update(ind):
frame = frames[ind]
ind += 1
print(ind)
if ind>30: #With this condition it will play gif infinitely
ind = 0
label.configure(image=frame)
root.after(100, update, ind)
label = Label(root)
label.pack()
root.after(0, update, 0)
root.mainloop()
A very simple approach would be to use multithreading.
To run the GIF infinitely in a Tkinter window you should follow the following:
Create a function to run the GIF.
Put your code to run the GIF inside while True inside the function.
Create a thread to run the function.
Run root.mainloop() in the primary flow of the program.
Use time.sleep() to control the speed of your animation.
Refer to my code below:
i=0
ph = ImageTk.PhotoImage(Image.fromarray(imageframes[i]))
imglabel=Label(f2,image=ph)
imglabel.grid(row=0,column=0)
def runthegif(root,i):
while True:
i = i + 7
i= i % 150
ph=ImageTk.PhotoImage(PhotoImage(file='images/ball.gif',format='gif -index %i' %i))
imagelabel=Label(f2,image=ph)
imagelabel.grid(row=0,column=0)
time.sleep(0.1)
t1=threading.Thread(target=runthegif,args=(root,i))
t1.start()
root.mainloop()
This question already has answers here:
Play an Animated GIF in python with tkinter
(3 answers)
Closed 5 years ago.
I've been trying to play an animated gif using Tkinter.PhotoImage, but haven't been seeing any success. It displays the image, but not the animation. The following is my code:
root = Tkinter.Tk()
photo = Tkinter.PhotoImage(file = "path/to/image.gif")
label = Tkinter.Label(image = photo)
label.pack()
root.mainloop()
It displays the image in a window, and that's it. I'm thinking that the issue has something to do with Tkinter.Label but I'm not sure. I've looked for solutions but they all tell me to use PIL (Python Imaging Library), and it's something that I don't want to use.
With the answer, I created some more code (which still doesn't work...), here it is:
from Tkinter import *
def run_animation():
while True:
try:
global photo
global frame
global label
photo = PhotoImage(
file = photo_path,
format = "gif - {}".format(frame)
)
label.configure(image = nextframe)
frame = frame + 1
except Exception:
frame = 1
break
root = Tk()
photo_path = "/users/zinedine/downloads/091.gif"
photo = PhotoImage(
file = photo_path,
)
label = Label(
image = photo
)
animate = Button(
root,
text = "animate",
command = run_animation
)
label.pack()
animate.pack()
root.mainloop()
Thanks for everything! :)
You have to drive the animation yourself in Tk. An animated gif consists of a number of frames in a single file. Tk loads the first frame but you can specify different frames by passing an index parameter when creating the image. For example:
frame2 = PhotoImage(file=imagefilename, format="gif -index 2")
If you load up all the frames into separate PhotoImages and then use timer events to switch the frame being shown (label.configure(image=nextframe)). The delay on the timer lets you control the animation speed. There is nothing provided to give you the number of frames in the image other than it failing to create a frame once you exceed the frame count.
See the photo Tk manual page for the official word.
Here's a simpler example without creating an object:
from tkinter import *
import time
import os
root = Tk()
frameCnt = 12
frames = [PhotoImage(file='mygif.gif',format = 'gif -index %i' %(i)) for i in range(frameCnt)]
def update(ind):
frame = frames[ind]
ind += 1
if ind == frameCnt:
ind = 0
label.configure(image=frame)
root.after(100, update, ind)
label = Label(root)
label.pack()
root.after(0, update, 0)
root.mainloop()
I am having two or more python Tkinter files. Each file is opening one window, how can run all the Tkinter windows functionality in one main window.
Ex : I have two files one is usbcam.py which will open USB camera and give the video steaming and the other one is ipcam.py it opens the IP camera and give the live streaming.This two files are opening in two windows how can make this to work in one window
usbcam.py
import cv2
import PIL.Image
import PIL.ImageTk
import Tkinter as tk
def update_image(image_label, cv_capture):
cv_image = cv_capture.read()[1]
cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
pil_image = PIL.Image.fromarray(cv_image)
pil_image.save('image3.jpg')
tk_image = PIL.ImageTk.PhotoImage(image=pil_image)
image_label.configure(image=tk_image)
image_label._image_cache = tk_image # avoid garbage collection
root.update()
def update_all(root, image_label, cv_capture):
if root.quit_flag:
root.destroy() # this avoids the update event being in limbo
else:
update_image(image_label, cv_capture)
root.after(10, func=lambda: update_all(root, image_label, cv_capture))
if __name__ == '__main__':
cv_capture = cv2.VideoCapture()
cv_capture.open(0) # have to use whatever your camera id actually is
root = tk.Tk()
setattr(root, 'quit_flag', False)
def set_quit_flag():
root.quit_flag = True
root.protocol('WM_DELETE_WINDOW', set_quit_flag) # avoid errors on exit
image_label = tk.Label(master=root) # the video will go here
image_label.pack()
root.after(0, func=lambda: update_all(root, image_label, cv_capture))
root.mainloop()
ipcam.py
import cv2
import numpy as np
import PIL.Image
import PIL.ImageTk
import Tkinter as tk
import urllib
stream = urllib.urlopen("http://192.168.2.195:80/capture/scapture").read()
bytes_ = ''
def update_image(image_label):
global bytes_
bytes_ += stream.read(1024)
a = bytes_.find('\xff\xd8')
b = bytes_.find('\xff\xd9')
if (a != -1) and (b != -1):
jpg = bytes_[a:b+2]
bytes_ = bytes_[b+2:]
cv_image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),
cv2.CV_LOAD_IMAGE_COLOR)
cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
pil_image = PIL.Image.fromarray(cv_image)
tk_image = PIL.ImageTk.PhotoImage(image=pil_image)
image_label.configure(image=tk_image)
image_label._image_cache = tk_image # avoid garbage collection
root.update()
def update_all(root, image_label):
if root.quit_flag:
print "coming if"
root.destroy() # this avoids the update event being in limbo
else:
print "coming else"
update_image(image_label)
root.after(1, func=lambda: update_all(root, image_label))
def timer(interval = 100):
root.after(0, func=lambda: update_all(root, image_label))
#.................................................................................................
root.after(interval, timer)
if __name__ == '__main__':
root = tk.Tk()
setattr(root, 'quit_flag', False)
def set_quit_flag():
root.quit_flag = True
root.protocol('WM_DELETE_WINDOW', set_quit_flag)
image_label = tk.Label(master=root) # label for the video frame
image_label.pack()
root.after(2, func=lambda: update_all(root, image_label))
# timer()
root.mainloop()
You need to designate one script as the main script, and in that one you can import the other. Here's an example of doing this using a simple subclass of the Frame widget:
The primary script (tkA.py):
from Tkinter import *
from tkB import Right # bring in the class Right from secondary script
class Left(Frame):
'''just a frame widget with a white background'''
def __init__(self, parent):
Frame.__init__(self, parent, width=200, height=200)
self.config(bg='white')
if __name__ == "__main__":
# if this script is run, make an instance of the left frame from here
# and right right frame from tkB
root = Tk()
Left(root).pack(side=LEFT) # instance of Left from this script
Right(root).pack(side=RIGHT) # instance of Right from secondary script
root.mainloop()
The secondary script (tkB.py):
from Tkinter import *
class Right(Frame):
'''just a frame widget with a black background'''
def __init__(self, parent):
Frame.__init__(self, parent, width=200, height=200)
self.config(bg='black')
if __name__ == "__main__":
# if this script is run, just do this:
root = Tk()
Right(root).pack()
root.mainloop()
Hope that helps.
First, you need to include it in the top. So in the top of ipcam.py write 'import usbcam' (without quotations).
For some reason, I was able to get this TKinter frame (allValOuterFrame) to expand both vertically and horizontally when its window is resized, but however, it appears that the canvas that the frame holds, as well as the frame and vertical scrollbar inside that canvas, will only expand horizontally. Could someone please explain why?
Here is my code:
# At first I only had "from X import *" but then discovered that
# it is bad practice, so I also included "import X" statements so
# that if I need to use something from tk or ttk explicitly, I can,
# but I had 2/3 of my code done at that point so I had to leave in the
# "import *" things.
try:
from Tkinter import * #python 2
import Tkinter as tk
from ttk import *
import ttk
import tkMessageBox as msg
import tkFileDialog as openfile
except ImportError:
from tkinter import * #python 3
import tkinter as tk
from tkinter.ttk import *
import tkinter.ttk as ttk
from tkinter import messagebox as msg
from tkinter import filedialog as openfile
import csv
# My stuff:
from extractor import Analysis
from extractor import createDictionariesAndLists as getRawData
from nitrogenCorrector import correct as nCorrect
from carbonCorrector import correct as cCorrect
( ... )
def createAllValWindow(self):
allValWindow = Toplevel(self)
allValWindow.grab_set()
if self.element == "N":
allValWindow.title("All Nitrogen Raw Data Values")
elif self.element == "C":
allValWindow.title("All Carbon Raw Data Values")
else:
allValWindow.title("All Raw Data Values")
allValOuterFrame = tk.Frame(allValWindow,background="#00FF00")
allValCanvas = Canvas(allValOuterFrame, borderwidth=0)
allValInnerFrame = Frame(allValCanvas, borderwidth=5)
def allValOnFrameConfigure(event):
allValCanvas.configure(scrollregion=allValCanvas.bbox("all"))
allValOuterFrame.grid_rowconfigure(0,weight=1)
allValOuterFrame.grid_columnconfigure(0,weight=1)
allValInnerFrame.grid_rowconfigure(0,weight=1)
allValInnerFrame.grid_columnconfigure(0,weight=1)
allValVertScrollbar = Scrollbar(allValOuterFrame, orient="vertical",command=allValCanvas.yview)
allValHorizScrollbar = Scrollbar(allValOuterFrame, orient="horizontal",command=allValCanvas.xview)
allValCanvas.configure(yscrollcommand=allValVertScrollbar.set, xscrollcommand=allValHorizScrollbar.set)
allValVertScrollbar.grid(row=1,column=12,sticky=N+S)
allValHorizScrollbar.grid(row=2,column=0,columnspan=12,sticky=E+W)
allValCanvas.grid(row=1,column=0,columnspan=12,sticky=N+S+E+W) allValCanvas.create_window((4,4),window=allValInnerFrame,anchor="nw",tags="allValInnerFrame")
allValInnerFrame.bind("<Configure>",allValOnFrameConfigure)
allValDoneButton = Button(allValWindow,text="Done",command=allValWindow.destroy)
allValOuterFrame.pack(fill="both",expand=1)
allValDoneButton.pack()
textRows = [self.rawHeader]
textLabels = [[]]
numDiffAminos = len(self.analyses) - 1 # Ignore the "trash" list at the end
for singleAminoAnalyses in self.analyses[0:numDiffAminos]: # Once again, ignoring the last list
if len(singleAminoAnalyses) < 1:
continue
for analysis in singleAminoAnalyses:
textRows.append([str(analysis.analysisID),
str(analysis.row),
str(analysis.identifier1),
str(analysis.identifier2),
str(analysis.comment),
str(analysis.peakNumber),
str(analysis.rt),
str(analysis.component),
str(analysis.areaAll),
str(analysis.ampl),
str(analysis.r),
str(analysis.delta)])
textLabels.append([])
for i in range(len(textRows)):
if i == 0:
listRow = i
else:
listRow = i+1
for j in range(len(textRows[i])):
if i == 0:
textLabels[i].append(Label(allValInnerFrame,text=textRows[i][j],font=("Fixedsys",10,"bold")))
else:
textLabels[i].append(Label(allValInnerFrame,text=textRows[i][j]))
if j == 9:
textLabels[i][j].grid(row=listRow,column=j,sticky=W+E,padx=(4,10))
else:
textLabels[i][j].grid(row=listRow,column=j,sticky=W+E,padx=(4,4))
if i == 0:
separator = tk.Frame(allValInnerFrame, height=2, borderwidth=1, bg="black", relief=SUNKEN)
separator.grid(row=1,column=0,columnspan=12,sticky=W+E)
It is because you give row 0 of AllValOuterFrame a weight of 1, but you put the canvas in row 1. If you move the canvas to row 0 or give row 1 a weight of 1, it will resize the way you expect.