如何使用Python的Tkinter实现点击按钮切换Canvas背景色
Simple Tkinter Canvas Background Color Switcher (No Classes)
Hey there! I put together a simple, class-free Tkinter script that does exactly what you're asking for—cycles the Canvas background from red to blue to yellow (and loops back if you keep clicking, though you can tweak that behavior easily if needed). Here's the code:
import tkinter as tk def switch_color(): # Update the color index to cycle through our list global color_index color_index = (color_index + 1) % len(colors) # Apply the new background color to the Canvas canvas.config(bg=colors[color_index]) # Set up the main application window root = tk.Tk() root.title("Canvas Color Toggle") # Define our color sequence: starts with red, then blue, then yellow colors = ["red", "blue", "yellow"] color_index = 0 # Start at the first color (red) # Create the Canvas with initial red background canvas = tk.Canvas(root, width=400, height=300, bg=colors[color_index]) canvas.pack(padx=10, pady=10) # Add a button directly onto the Canvas (positioned at the center) toggle_btn = tk.Button(canvas, text="Switch Background", command=switch_color) canvas.create_window(200, 150, window=toggle_btn) root.mainloop()
Quick breakdown of how it works:
- We use a global
color_indexvariable to track which color we're currently on—this lets us cycle through thecolorslist without needing a class to hold state. - The
switch_color()function increments the index (using modulo%to loop back to the start after the last color) and updates the Canvas background withcanvas.config(bg=...). - The button is placed directly on the Canvas using
create_window()instead of packing it to the main window, so it stays anchored to the Canvas as expected.
If you want to adjust the color sequence or add more colors, just update the colors list—everything else will work automatically!
内容的提问来源于stack exchange,提问作者Victor Dorian
相关产品推荐
相关产品推荐

