level and coins increases as the button is pressed - python

We just started Tkinter and as our professor in programming asked us if we could try to make a game using Tkinter as our final project in 1st year college, specifically 4 pics 1 word, I need assistance as to how can I increase the level to +1 and the coins to +10 whenever the next button is pressed? any insights are very much appreciated. The code and sample output is given below for reference
from distutils.cmd import Command
from tkinter import *
from turtle import heading, width
from PIL import Image, ImageTk
root = Tk()
root.title("4 pics 1 word")
root.geometry("500x650")
root.maxsize(500,650)
root.iconbitmap ("4picslogo.ico")
#Variable
levelno = 1
coins = 100
counter = 0
picNum = 0
#def
def nextlevel():
global levelno
levelno = levelno + 1
if levelno==50:
levelno=1
global coins
coins = coins + 10
def changeImage():
global picNum
picNum+=1
if picNum==50:
picNum=0
pics.config(file=picfiles[picNum]+".png")
nextPic.config(text="PASS "+str(picNum+1))
#Frames
frame_1 = Frame(root, width=500, height=150)
frame_1.pack (side=TOP)
frame_2 = Frame(root,width=500, height=300)
frame_2.pack ()
frame_3 = Frame(root, width=500, height=200)
frame_3.pack ()
#FrameOne (Level and coins bar)
Blue_bar = Label (frame_1, width=71,height=5,bg="#4472c4")
Blue_bar.grid()
levelcounter = Label (frame_1, text="Level: "+str(levelno), font=("Helvetica",25,"bold"),fg="white",bg="#4472c4")
levelcounter.grid(row=0,column=0,sticky=W)
coinimg = PhotoImage(file="coins.png")
coins_pic = Canvas(frame_1, width=55, height=55, bg="#4472c4")
coins_pic.create_image(30,30, image=coinimg)
coins_pic.grid(row=0,column=0,padx=(320,0))
coin_counter = Label (frame_1, text=""+str(coins), font=("Helvetica",25,"bold"),fg="white",bg="#4472c4")
coin_counter.grid(row=0,column=0,sticky=E,padx=(0,1))
#FrameTwo (Pictures to guess)
################################################################################################################################
f = open("picList.txt","r")
x = f.readlines()
picfiles = list()
for p in x:
fn = p.strip().split(';')
picfiles.append(fn[1])
pics = PhotoImage(file=picfiles[0]+".png")
pic_viewer = Label(frame_2,image=pics)
pic_viewer.grid(row=0,column=0,pady=(40,0))
################################################################################################################################
#FrameThree (Buttons)
button_picture_pass = PhotoImage(file='pass.png')
nextPic = Button(frame_3,image=button_picture_pass,text=""+str(levelno+1),command=lambda:[changeImage(), nextlevel()])
nextPic.grid(padx=(400,0),pady=(135,0))
quitbutton = Button(root,text="Save and Quit", command = root.quit)
quitbutton.pack(anchor=E,padx=(0,22))
root.mainloop()

Updating levelno and coins will not update levelcounter and coin_counter automatically. You need to update them inside nextlevel():
def nextlevel():
global levelno, coins
levelno += 1
if levelno == 50:
levelno = 1
coins += 10
# update counter labels
levelcounter['text'] = f'Level: {levelno}'
coin_counter['text'] = coins

I'm not familiar with this code but do have some experience in writing code in general.
it seems the thing you want is already in this function
def nextlevel():
global levelno
levelno = levelno + 1
if levelno==50:
levelno=1
global coins
coins = coins + 10
and here you define the Next button:
button_picture_pass = PhotoImage(file='pass.png')
and here you trigger the function to increase the level and money when pressed:
nextPic = Button(frame_3,image=button_picture_pass,text=""+str(levelno+1),command=lambda:[changeImage(), nextlevel()])
so I'm not sure what the question is :D

Related

How can I use a single button to pause and unpause timer in tkinter? (without using pygame)

I'm working on a simple timer that counts down 30 mins for me to study and 5 mins for a break. So far, the start_timer function and count_down function work well, I just cannot figure out how to write the pause function. I did some research for a few days. Most articles are using pygame or to bind with different keys. I am wondering what function I should use for one tkinter button to pause/unpause my timer if something comes up and I want to pause the timer till I'm back.
Thank you #TimRoberts, I can pause the timer now. However, I don't know how to unpause the timer to let it continue counting down.
from tkinter import *
import math
WORK_MIN = 30
BREAK_MIN = 5
reps = 0
paused = False
# --------------------------- TIMER ---------------------------- #
def start_timer():
global reps
reps += 1
work_sec = WORK_MIN * 60
break_sec = BREAK_MIN * 60
if reps % 2 == 1:
title_label.config(text="Study")
count_down(work_sec)
else:
title_label.config(text="Break")
count_down(break_sec)
window.attributes('-topmost', 0)
# ------------------------ COUNTDOWN--------------------------- #
def count_down(count):
global paused
count_min = math.floor(count / 60)
count_sec = count % 60
if count_min < 10:
count_min = f"0{count_min}"
if count_sec < 10:
count_sec = f"0{count_sec}"
canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}" )
if count > 0:
if not paused:
count -= 1
window.after(1000, count_down, count-1)
else:
start_timer()
# ---------------------------- PAUSE ------------------------------- #
def pause_function():
global paused
paused = not paused
# ---------------------------- UI ------------------------------- #
window = Tk()
title_label = Label(text="Timer")
title_label.grid(column=1, row=0)
check_marks = Label(text="")
check_marks.grid(column=1, row=4)
canvas = Canvas(width=200, height=224, bg="lightblue")
timer_text = canvas.create_text(100, 128, text="00:00", fill="white", font=("Courier", 45, "bold"))
canvas.grid(column=1, row=1)
start_button = Button(text="Start", command=start_timer)
start_button.grid(column=0, row=2)
pause_button = Button(text="Pause", command=pause_function)
pause_button.grid(column=2, row=2)
window.mainloop()
You need to do the "after" call even if you're paused, otherwise you'll never notice when you unpause. Also, since you're decrementing count once, you don't need to do it again:
def count_down(count):
count_min = count // 60
count_sec = count % 60
canvas.itemconfig(timer_text, text=f"{count_min:02d}:{count_sec:02d}" )
if count:
if not paused:
count -= 1
window.after(1000, count_down, count)
else:
start_timer()
If you want to be tricky, you could use:
if count:
count -= not paused
since True is 1 and False is 0.

I'm making a snake game using python. I cant seem to make the snake moves in any direction. What should i fix and add with my codes?

I have this code below where it will add a +1 or -1 unit whenever I press any of the arrow button. My question is how can I use that new value in velocity and add it to my snake to the snake moves? I believe my code is wrong in the def snake() function but I don't seem to find the solution.
additional: what else should I fix to my code here to make it cleaner and concise? thank you
import random
from tkinter import *
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
SCORE = 0
BODY_SIZE = 10
SNAKE_COLOUR ="blue"
SNAKE_FOOD = "purple"
def food():
x = random.randint(0,30-1)*BODY_SIZE
y = random.randint(0,30-1)*BODY_SIZE
canvas.create_rectangle (x,y,x+BODY_SIZE,y+BODY_SIZE,fill="GOLD")
def snake():
SNAKE_VELOCITY_X = 0
SNAKE_VELOCITY_Y = 0
snakeX = 0
snakeY = 0
snakeX = snakeX + SNAKE_VELOCITY_X
snakeY = snakeY + SNAKE_VELOCITY_Y
canvas.create_rectangle (snakeX,snakeY,snakeX+BODY_SIZE,snakeY+BODY_SIZE,fill="blue")
def update():
food()
snake()
master =Tk()
master.geometry("%sx%s"%(SCREEN_WIDTH,SCREEN_HEIGHT))
labelName= Label(master, text="A python game!", font= ('Courier 10 underline'))
labelScore = Label(master, text="%s"%(SCORE), font=('Courier 10'))
labelName.pack()
labelScore.pack()
canvas = Canvas(master, bg="black",width=300,height=300)
canvas.pack()
update()
def right_direction(event):
SNAKE_VELOCITY_X = 1
SNAKE_VELOCITY_Y = 0
print(SNAKE_VELOCITY_X)
def left_direction(event):
SNAKE_VELOCITY_X = -1
SNAKE_VELOCITY_Y = 0
print(SNAKE_VELOCITY_X)
def up_direction(event):
SNAKE_VELOCITY_X = 0
SNAKE_VELOCITY_Y = 1
print(SNAKE_VELOCITY_Y)
def down_direction(event):
SNAKE_VELOCITY_X = 0
SNAKE_VELOCITY_Y = -1
print(SNAKE_VELOCITY_Y)
master.bind("<Right>", right_direction)
master.bind("<Left>", left_direction)
master.bind("<Up>", up_direction)
master.bind("<Down>", down_direction)
master.mainloop()
This is not an exhaustive answer, but should get you moving in the right direction. First, the concept: you create objects with the create_...() functions, and those functions return "handles" to the created objects. you can then use the handles to move, etc. the objects. To actually redraw the screen, you need to call the Tk.update() function.
Roughly, you need to change number of things:
the function canvas.create_rectangle(...) returns a handle to the rectangle. Save it, this is your "snake"
snakeHandle=canvas.create_rectangle(...)
then, when you execute one of your functions ..._direction(event), inside that function, tell the snake to move somewhere like this:
canvas.move(snakeHandle,x_distance, y_distance)
then kick tkinter so it updates the screen:
master.update()
i changed a couple off things and now it should move. but the only problem is that the the snake does not get removed after it moves. you can try canvas.delete().
i put a # after everything i changed.
import random
from tkinter import *
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
SCORE = 0
BODY_SIZE = 10
SNAKE_COLOUR ="blue"
SNAKE_FOOD = "purple"
SNAKE_VELOCITY_X = 0 # making these variables avalable to the whole code
SNAKE_VELOCITY_Y = 0 #
snakeX = 0 #
snakeY = 0 #
def food():
x = random.randint(0,30-1)*BODY_SIZE
y = random.randint(0,30-1)*BODY_SIZE
canvas.create_rectangle (x,y,x+BODY_SIZE,y+BODY_SIZE,fill="GOLD")
def snake():
global snakeX, snakeY, SNAKE_VELOCITY_X, SNAKE_VELOCITY_Y # global makes it so that the change is not only for the function but for the entire code
snakeX = snakeX + SNAKE_VELOCITY_X * BODY_SIZE # makes it so that the player moves on player size instead of one pixel
snakeY = snakeY + SNAKE_VELOCITY_Y * BODY_SIZE #
canvas.create_rectangle (snakeX,snakeY,snakeX+BODY_SIZE,snakeY+BODY_SIZE,fill="blue")
def update():
#food() # otherwise spawns new food
snake()
master =Tk()
master.geometry("%sx%s"%(SCREEN_WIDTH,SCREEN_HEIGHT))
labelName= Label(master, text="A python game!", font= ('Courier 10 underline'))
labelScore = Label(master, text="%s"%(SCORE), font=('Courier 10'))
labelName.pack()
labelScore.pack()
canvas = Canvas(master, bg="black",width=300,height=300)
canvas.pack()
update()
def right_direction(event):
global SNAKE_VELOCITY_X, SNAKE_VELOCITY_Y #
SNAKE_VELOCITY_X = 1
SNAKE_VELOCITY_Y = 0
print(SNAKE_VELOCITY_X)
update() # calling the update function
def left_direction(event):
global SNAKE_VELOCITY_X, SNAKE_VELOCITY_Y #
SNAKE_VELOCITY_X = -1
SNAKE_VELOCITY_Y = 0
print(SNAKE_VELOCITY_X)
update() #
def up_direction(event):
global SNAKE_VELOCITY_X, SNAKE_VELOCITY_Y #
SNAKE_VELOCITY_X = 0
SNAKE_VELOCITY_Y = -1
print(SNAKE_VELOCITY_Y)
update() #
def down_direction(event):
global SNAKE_VELOCITY_X, SNAKE_VELOCITY_Y #
SNAKE_VELOCITY_X = 0
SNAKE_VELOCITY_Y = 1
print(SNAKE_VELOCITY_Y)
update() #
master.bind("<Right>", right_direction)
master.bind("<Left>", left_direction)
master.bind("<Up>", up_direction)
master.bind("<Down>", down_direction)
master.mainloop()
hope this helps
EDIT
i change your code to be in a class and cleaned some things up
import random
from tkinter import *
class game(Tk):
def __init__(self):
super().__init__()
self.createVariables()
self.createWindow()
self.bindControls()
self.snake()
self.food()
def createVariables(self):
self.SCREEN_WIDTH = 500
self.SCREEN_HEIGHT = 500
self.SCORE = 0
self.BODY_SIZE = 10
self.SNAKE_COLOUR ="blue"
self.SNAKE_FOOD = "purple"
self.SNAKE_VELOCITY_X = 0
self.SNAKE_VELOCITY_Y = 0
self.snakeX = 0
self.snakeY = 0
self._snake = None
def createWindow(self):
self.geometry("%sx%s"%(self.SCREEN_WIDTH,self.SCREEN_HEIGHT))
self.labelName= Label(self, text="A python game!", font= ('Courier 10 underline'))
self.labelScore = Label(self, text="%s"%(self.SCORE), font=('Courier 10'))
self.labelName.pack()
self.labelScore.pack()
self.canvas = Canvas(self, bg="black",width=300,height=300)
self.canvas.pack()
def bindControls(self):
self.bind("<Right>", self.right_direction)
self.bind("<Left>", self.left_direction)
self.bind("<Up>", self.up_direction)
self.bind("<Down>", self.down_direction)
def food(self):
x = random.randint(0,30-1)*self.BODY_SIZE
y = random.randint(0,30-1)*self.BODY_SIZE
self._food = self.canvas.create_rectangle (x,y,x+self.BODY_SIZE,y+self.BODY_SIZE,fill="GOLD")
def snake(self):
if self._snake != None:
self.canvas.delete(self._snake)
self.snakeX = self.snakeX + self.SNAKE_VELOCITY_X * self.BODY_SIZE
self.snakeY = self.snakeY + self.SNAKE_VELOCITY_Y * self.BODY_SIZE
self._snake = self.canvas.create_rectangle (self.snakeX,self.snakeY,self.snakeX+self.BODY_SIZE,self.snakeY+self.BODY_SIZE,fill="blue")
def update(self):
self.snake()
def right_direction(self, event):
self.SNAKE_VELOCITY_X = 1
self.SNAKE_VELOCITY_Y = 0
print(self.SNAKE_VELOCITY_X)
self.update()
def left_direction(self, event):
self.SNAKE_VELOCITY_X = -1
self.SNAKE_VELOCITY_Y = 0
print(self.SNAKE_VELOCITY_X)
self.update()
def up_direction(self, event):
self.SNAKE_VELOCITY_X = 0
self.SNAKE_VELOCITY_Y = -1
print(self.SNAKE_VELOCITY_Y)
self.update()
def down_direction(self, event):
self.SNAKE_VELOCITY_X = 0
self.SNAKE_VELOCITY_Y = 1
print(self.SNAKE_VELOCITY_Y)
self.update()
if __name__ == "__main__":
run = game()
run.mainloop()
hope it helps

Python Tkinter move one image with position in chess game

I made a chess game in Python with Tkinter, but I've a huge problem.
The piece is generated by a matrix. But, When a case is empty or when I moved a piece, I can't wish(delete) the case. I want to wish(delete) only a piece with cordonnate or just move image of one piece (I don't khnow if it's possible), any one help?
The code:
from tkinter import *
from PIL import Image
import math
root = Tk()
root.title("Game")
frame = Frame(root)
frame.pack()
canvas = Canvas(frame, bg="black", width=500, height=500)
canvas.pack()
background = PhotoImage(file="image/Chessboard.png")
canvas.create_image(250,250,image=background)
pion = PhotoImage(file="image/W_pion.png")
Matrixe= [["","","","","","","",""],
["","","","","","","",""],
["","","","","","","",""],
["","","","","","","",""],
["","","","","","","",""],
["","","","","","","",""],
["W_Pion","W_Pion","W_Pion","W_Pion","W_Pion","W_Pion","W_Pion","W_Pion"],
["","","","","","","",""]]
ligne=len(Matrixe)
col=len(Matrixe[0])
def actu():
for l in range(ligne):
for c in range(col):
if Matrixe[c][l] == "W_Pion":
canvas.create_image(62.5 * l + 33,62.5 * c + 33,image=pion)
actu()
#mouse input
def getorigin(eventorigin):
global Posx,Posy, i, piece
Posx = eventorigin.x
Posy = eventorigin.y
Xcase = math.ceil((Posx / 62)) - 1
Ycase = math.ceil((Posy / 62)) - 1
if Matrixe[Ycase][Xcase] != "":
global preY , preX, piece
piece = Matrixe[Ycase][Xcase]
i = 1
preY = Ycase
preX = Xcase
print(piece)
if canvas.bind("<Button-1>") and Matrixe[Ycase][Xcase] == "":
Matrixe[Ycase][Xcase] = piece
Matrixe[preY][preX] = ""
print(Matrixe[preY][preX])
actu()
canvas.bind("<Button-1>", getorigin)
root.title("Chess")
root.iconbitmap("icon.ico")
root.geometry("500x500")
root.mainloop()
It is because you did not delete the previous set of chess pieces before creating new set of chess pieces inside actu().
Create the chess pieces with a tag, for example 'piece', then you can delete old set of chess pieces using that tag:
def actu():
canvas.delete('piece') # delete old chess pieces
for l in range(ligne):
for c in range(col):
if Matrixe[c][l] == "W_Pion":
canvas.create_image(62.5*l+33, 62.5*c+33, image=pion, tag='piece')
However, better approach is just to move the piece selected instead of recreate the set of pieces:
def actu():
for l in range(ligne):
for c in range(col):
if Matrixe[c][l] == "W_Pion":
# replace cell content by the canvas item ID
Matrixe[c][l] = canvas.create_image(62.5*l+33, 62.5*c+33, image=pion, tag=Matrixe[c][l])
actu()
piece = None
def getorigin(eventorigin):
global preX, preY, piece
Posx = eventorigin.x
Posy = eventorigin.y
Xcase = math.ceil((Posx / 62)) - 1
Ycase = math.ceil((Posy / 62)) - 1
if Matrixe[Ycase][Xcase] != "":
# select the piece
piece = Matrixe[Ycase][Xcase]
preY = Ycase
preX = Xcase
elif piece:
# a piece is selected, so move the piece
canvas.coords(piece, Xcase*62.5+33, Ycase*62.5+33)
Matrixe[Ycase][Xcase] = piece
Matrixe[preY][preX] = ""
piece = None # deselect the piece

How do you disable a button when it is clicked?

I am new to python, and self taught. I am trying to make a simplifed minesweeper game called "Mines". This game has a 5 by 5 grid of buttons, with a random number of mines. Everything is working fine, except for one issue. After you click a safe space, the button should be disabled so you cannot gain any more points. With my code, I have no idea how to do this.
I did already try to call a method to disable the button, as well as using the DISABLED command. Neither worked. I want the "white" buttons to be disabled after click, as those are the safe spaces. In a perfect world, I will call the disable() method when the button is clicked and use that method to disable that button.
##Create the canvas of the board.
window = Tk ()
window.title("Mines Game")
window.geometry('819x655')
##Scoring function. The first box clicked awards 1 point, and after that each box is worth double your total points.
def score():
global scores
if (scores == 0):
scores = scores + 1
print ("Safe space hit! You have " + str(scores) + " point.")
else:
scores = scores * 2
print ("Safe space hit! You have " + str(scores) + " points.")
def squares():
##Main method of creating a 5x5 square of buttons.
global scores
scores = 0
less_bombs = True
r = -1
c = 0
x = 0
if less_bombs:
for i in range(5):
r = r + 1
for l in range(5):
y = randint(0,25)
if x == 5:
y = 10
if y < 6:
btn = Button(window, bg = "red", command=end)
btn.grid(column = c,row = r)
#btn.grid(sticky="nesw")
btn.config(height = 8, width = 22)
x = x + 1
else:
btn = Button(window, bg = "white", command=lambda:[score(),DISABLED])
btn.grid(column = c,row = r)
#btn.grid(sticky="nesw")
btn.config(height = 8, width = 22)
c = c + 1
c = 0
def end():
##This method creates the popup after you click a mine.
end = Tk ()
end.title ('Game Over!')
end.geometry ('300x161')
btn = Button(end, text ="Close game", command=close)
btn.grid(column = 0,row = 0)
#btn.grid(sticky="nesw")
btn.config(height = 10, width = 20)
btn = Button(end, text ="Reset game", command=lambda:[reset(),end.destroy()])
btn.grid(column = 1,row = 0)
#btn.grid(sticky="nesw"
btn.config(height = 10, width = 20)
if (scores == 1):
print ("Game over! You hit a mine :(")
print ("Your score for that game was " + str(scores) + " point.")
if (scores != 1):
print ("Game over! You hit a mine :(")
print ("Your score for that game was " + str(scores) + " points.")
def disable():
pass
def close():
sys.exit()
def reset():
squares()
squares()
window.mainloop()
I want the button to be disabled after being clicked, however currently the player can click the button as many times as he or she wants.
You can fix it by changing creation of white Buttonss as indicated below in ALL CAPS. This gives the lambda function a default value for btn which changes each iteration of loop (otherwise the function would always refer to the last one created in the for loop).
def squares():
""" Main method of creating a 5x5 square of buttons. """
global scores
scores = 0
less_bombs = True
r = -1
c = 0
x = 0
if less_bombs:
for i in range(5):
r = r + 1
for l in range(5):
y = randint(0,25)
if x == 5:
y = 10
if y < 6:
btn = Button(window, bg="red", command=end)
btn.grid(column=c, row=r)
#btn.grid(sticky="nesw")
btn.config(height=8, width=22)
x = x + 1
else:
btn = Button(window, bg="white") ## REMOVE command= OPTION. ##
btn.grid(column=c, row=r)
#btn.grid(sticky="nesw")
btn.config(height=8, width=22, # USE command SHOWN BELOW. ##
command=lambda btn=btn: [score(), btn.config(state=DISABLED)])
c = c + 1
c = 0

Tkinter Image Viewer Method

I am an atmospheric scientist, struggling through python (2.7 using PIL and Tkinter) in an attempt to create a simple image viewer that will display some of the forecast products we eventually produce. I would like to implement a start, stop, forward, backward, and loop button. The loop button and its associated callback currently work correctly. The loop method is credited to Glenn Pepper (found an open-source project via google).
Here is the code:
from Tkinter import *
from PIL import Image, ImageTk
import tkMessageBox
import tkFileDialog
#............................Button Callbacks.............................#
root = Tk()
root.title("WxViewer")
root.geometry("1500x820+0+0")
def loop():
StaticFrame = []
for i in range(0,2):
fileName="filename"+str(i)+".gif"
StaticFrame+=[PhotoImage(file=fileName)]
def animation(currentframe):
def change_image():
displayFrame.create_image(0,0,anchor=NW,
image=StaticFrame[currentframe], tag='Animate')
# Delete the current picture if one exist
displayFrame.delete('Animate')
try:
change_image()
except IndexError:
# When you get to the end of the list of images -
#it simply resets itself back to zero and then we start again
currentframe = 0
change_image()
displayFrame.update_idletasks() #Force redraw
currentframe = currentframe + 1
# Call loop again to keep the animation running in a continuous loop
root.after(1000, animation, currentframe)
# Start the animation loop just after the Tkinter loop begins
root.after(10, animation, 0)
def back():
print("click!")
def stop():
print("click!")
def play():
print("click!")
def forward():
print("click!")
#..........................ToolFrame Creation............................#
toolFrame = Frame(root)
toolFrame.config(bg="gray40")
toolFrame.grid(column=0,row=0, sticky=(N,W,E,S) )
toolFrame.columnconfigure(0, weight = 1)
toolFrame.rowconfigure(0, weight = 1)
toolFrame.pack(pady = 0, padx = 10)
backButton = Button(toolFrame, text="Back", command = back)
backButton.pack(side = LEFT)
stopButton = Button(toolFrame, text = "Stop", command = stop)
stopButton.pack(side = LEFT)
playButton = Button(toolFrame, text = "Play", command = play)
playButton.pack(side = LEFT)
forwardButton = Button(toolFrame, text = "Forward", command = forward)
forwardButton.pack(side = LEFT)
loopButton = Button(toolFrame, text = "Loop", command = loop)
loopButton.pack(side = LEFT)
toolFrame.pack(side = TOP, fill=X)
#........................DisplayFrame Creation..........................#
displayFrame = Canvas(root, width=1024,height=768)
displayFrame.config(bg="white")
displayFrame.grid(column=0,row=0, sticky=(N,W,E,S) )
displayFrame.columnconfigure(0, weight = 1)
displayFrame.rowconfigure(0, weight = 1)
displayFrame.pack(pady = 5, padx = 10)
displayFrame.pack(side = LEFT, fill=BOTH)
#...............................Execution...............................#
root.mainloop()
It is rather straightforward. I have searched GitHub for projects, google, and stackoverflow but I am unsure how to make these five methods play nicely with each other. Could anyone share some pointers on how I could construct these other four methods so that they work appropriately? Thank you for your time!
I would replace the current loop function with something like the following (untested). The changes: add some global names to share data between functions; make change_image do everything needed to change an image, given that current_image is valid; except for the starting value, make current_image be always a valid image number when it is changed; factor forward() out of animate() (which is just repeated times forward calls).
n_images = 2
images = [PhotoImage(file="filename"+str(i)+".gif") for i in range(n_images)]
current_image = -1
def change_image():
displayFrame.delete('Animate')
displayFrame.create_image(0,0, anchor=NW,
image=StaticFrame[current_image], tag='Animate')
displayFrame.update_idletasks() #Force redraw
callback = None
def animate():
global callback
forward()
callback = root.after(1000, animate)
Here are three of the other functions.
def forward():
global current_image
current_image += 1
if current_image >= n_images:
current_image = 0
change_image()
def back():
global current_image
current_image -= 1
if current_image < 0:
current_image = n_images-1
change_image()
def stop():
if callback is not None:
root.after_cancel(callback)

Categories