问题
I'm a beginner programmer in python and have recently began using tkinter though I have come across a problem which I can't solve.
Basically I have two entry boxes.
- Entry1 = message
- Entry2 = no. of flashes
(This is just an example of what I need.)
All I need is a for loop for a label to pop up and flash entry1 as many times as entry2, yes I realize how to get the entry inputs but I have no idea how to get the label to continuously flash, I have tried pack_forget and .destroy methods for the label in a loop, but unfortunately it does not display as it almost instantly clears it from the screen again.
回答1:
The basic idea is to create a function that does the flash (or half of a flash), and then use after to repeatedly call the function for as long as you want the flash to occur.
Here's an example that switches the background and foreground colors. It runs forever, simply because I wanted to keep the example short. You can easily add a counter, or a stop button, or anything else you want. The thing to take away from this is the concept of having a function that does one frame of an animation (in this case, switching colors), and then scheduling itself to run again after some amount of time.
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.label = tk.Label(self, text="Hello, world",
background="black", foreground="white")
self.label.pack(side="top", fill="both", expand=True)
self.flash()
def flash(self):
bg = self.label.cget("background")
fg = self.label.cget("foreground")
self.label.configure(background=fg, foreground=bg)
self.after(250, self.flash)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
来源:https://stackoverflow.com/questions/21419032/flashing-tkinter-labels