You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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_index variable to track which color we're currently on—this lets us cycle through the colors list 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 with canvas.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:52:51