如何减少按钮上的数字?

时间:2016-10-14 06:47:43

标签: python python-2.7 tkinter

我试图创建一个只有一个按钮的GUI。每次按下按钮,按钮上的数字都会减少。所以我写了这个:

import Tkinter

def countdown(x):        
   x -= 1

top = Tkinter.Tk()

def helloCallBack():    
    countdown(x)    

B = Tkinter.Button(top, text=x, command=helloCallBack )   
B.pack()       
top.mainloop()

我希望该按钮的文字像5 4 3 2 1,那么我应该在哪里放x=5

2 个答案:

答案 0 :(得分:2)

您可以创建全局变量并在函数countdown中使用它(但您必须使用global),然后您可以使用config(text=...)更改按钮上的文本。

import Tkinter as tk

# --- functions ---

def countdown():
    global x # use global variable

    x -= 1

    B.config(text=x)

# --- main ---

# create global variable (can be in any place - before/after function, before/after Tk())
x = 5

top = tk.Tk()

B = tk.Button(top, text=x, command=countdown)   
B.pack()

top.mainloop()    

或者您可以使用IntVar()textvariable - 因此您不需要config(text=...)global

import Tkinter as tk

# --- functions ---

def countdown():
    x.set( x.get()-1 )

# --- main ---

top = tk.Tk()

# create global variable (have to be after Tk())
x = tk.IntVar()
x.set(5)

# use `textvariable` and `lambda` to run `countdown` with `x`
B = tk.Button(top, textvariable=x, command=countdown)   
B.pack()

top.mainloop()

我使用lambdacountdown()一起运行x,因此我可以将countdown与多个按钮IntVar一起使用。 (当您使用int

时,在第一个示例中不能执行相同的操作
import Tkinter as tk

# --- functions ---

def countdown(var):
    var.set( var.get()-1 )

# --- main ---

top = tk.Tk()

# create global variable (have to be after Tk())
x = tk.IntVar()
x.set(5)

y = tk.IntVar()
y.set(5)

# use `textvariable` and `lambda` to run `countdown` with `x`
B1 = tk.Button(top, textvariable=x, command=lambda:countdown(x))   
B1.pack()

B2 = tk.Button(top, textvariable=y, command=lambda:countdown(y))   
B2.pack()

top.mainloop()

BTW:您可以使用after(miliseconds, functio_name)每1秒运行一次功能countdown并倒计时而不点击:)

import Tkinter as tk

# --- functions ---

def countdown(var):
    var.set( var.get()-1 )

    # run again time after 1000ms (1s)
    top.after(1000, lambda:countdown(var))

# --- main ---

top = tk.Tk()

# create global variable (have to be after Tk())
x = tk.IntVar()
x.set(5)

# use `textvariable` and `lambda` to run `countdown` with `x`
B = tk.Button(top, textvariable=x)   
B.pack()

# run first time after 1000ms (1s)
top.after(1000, lambda:countdown(x))

top.mainloop()

答案 1 :(得分:0)

http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/control-variables.html的“按钮”部分所述,您需要创建一个特殊的StringVar来使按钮动态更新。您可以将StringVar传递给textvariable构造函数的Button变量,并更新StringVar函数中的countdown()值。 http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/button.html指出textvariable

  

与此按钮上的文本关联的StringVar()实例。如果更改了变量,则新值将显示在按钮上。