In the code following there is a lot of bad flickering, the animations are not smooth,…
- User
In the code following there is a lot of bad flickering, the animations are not smooth, and some symbols appear to come out blank, can you improve this? maybe creating a strip of the png files and using canvas coords to animate might be a better solution towhat I have here? import random import tkinter as tk from PIL import Image, ImageTk
root = tk.Tk() root.title("Slot machine reels demo")
canvas_width = 340 canvas_height = 60 symbol_size = 60 num_symbols = 5 reel = [] symbol_photo = None symbol = None
symbols = {"bar": "bar.png", "cherry": "cherry.png", "coin": "coin.png", "lemon": "lemon.png", "plum": "plum.png", "tomatoe": "tom.png",} symbols_list = list(symbols.keys())
canvas = tk.Canvas(root, width=canvas_width, height=canvas_height) canvas.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
def get_a_rnd_symbol(): """ Choose a random symbol and store in symbol_photo. """ global symbol_photo, symbol symbol = random.choice(symbols_list) symbol_image = Image.open(symbols[symbol]) symbol_image = symbol_image.resize((symbol_size, symbol_size)) symbol_photo = ImageTk.PhotoImage(symbol_image)
def get_startup_rnd_symbols(): """ Get symbols to place on reels for start up.""" global symbol_photo, symbol for j in range(num_symbols): get_a_rnd_symbol() # choose a rnd symbol
codesymbol_label = canvas.create_image(j * (symbol_size + 10), 0, anchor=tk.NW, image=symbol_photo) reel.append((symbol_label, symbol_photo)) canvas.update()def spin_reel(j, count, stop_point): """ Spin a single reel. """ if count == stop_point: return
codeget_a_rnd_symbol() old_symbol_label, _ = reel[j] new_symbol_label = canvas.create_image(j * (symbol_size + 10), -symbol_size, anchor=tk.NW, image=symbol_photo) for k in range(symbol_size // 2): canvas.move(old_symbol_label, 0, 2) canvas.move(new_symbol_label, 0, 2) canvas.update() reel[j] = (new_symbol_label, symbol_photo) root.after(10, spin_reel, j, count+1, stop_point)def spin_reels(): """ Spin all reels. """ spin_btn.config(state="disabled") # to stop multiclicking
code - Assistant
- User
line 72, in spin_reel canvas.itemconfig(f"reel_{idx}", image=images_strip, subrectangle=(next_offset_x, 0, next_offset_x+symbol_size, symbol_size)) File "C:\python_376\lib\tkinter_init_.py", line 2578, in itemconfigure return self.configure(('itemconfigure', tagOrId), cnf, kw) File "C:\python_376\lib\tkinter_init.py", line 1476, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) _tkinter.TclError: unknown option "-subrectangle"
- Assistant
Apologies for the confusion. It looks like the "subrectangle" option is not available in the version of tkinter you are using.
As an alternative approach, we can create individual PhotoImage objects for each symbol and update accordingly. Here's the updated version of the code: