如何在点击按钮后将tkinter计数器重置为0?
Add Reset Functionality to Tkinter Counter
First, let's fix a small typo in your original code: you defined the increment function as OnClick (capital O), but the button's command uses onClick (lowercase o) — that'll throw a NameError if you run it. Let's fix that first, then add the reset feature you need.
Here's how to implement the reset functionality step by step:
- Create a dedicated function that sets the counter variable back to 0
- Add a second button that triggers this function when clicked
Full Modified Code
import tkinter import sys root = tkinter.Tk() root.geometry("200x200") root.title("His Button Increaser") counter = tkinter.IntVar() def OnClick(event=None): counter.set(counter.get() + 1) # New function to reset counter to 0 def resetCounter(): counter.set(0) tkinter.Label(root, textvariable=counter).pack(pady=10) tkinter.Button(root, text="One up", command=OnClick).pack(pady=5) # New reset button linked to the reset function tkinter.Button(root, text="Reset to 0", command=resetCounter).pack(pady=5) root.mainloop()
Key Changes Explained
- Fixed function name mismatch: The button's
commandnow correctly referencesOnClick(matches the function definition) to avoid runtime errors - Added
resetCounter()function: This straightforward function updates thecounterIntVar directly to 0 - Added the reset button: A new button labeled "Reset to 0" is added below the increment button, with small padding to keep the UI clean and spaced out
Run this code, and you'll be able to increment the counter with "One up" and reset it to 0 anytime using the new button!
内容的提问来源于stack exchange,提问作者Stavrius Mtvs
相关产品推荐
相关产品推荐

