2016-10-14 3 views
0

버튼이 하나 뿐인 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을 넣어해야합니다 그래서 내가 쓴?

+0

을 클릭하지 않고 기능 countdown 모든 1과 카운트 다운을 실행 after(miliseconds, functio_name)을 사용할 수 있습니다 왜 그 편집을 취소 했습니까? 믿을 수 없을만큼 분명하지 않은가? – jonrsharpe

+0

난 그냥 취소 했나요? 오, 하나님, 내 나쁜 생각은 그것이 제안이고 그것을 더 잘 coppied하고 그것을 만들려고 노력했다. –

답변

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() 

나는 내가 다른 IntVar 많은 버튼 countdown을 사용할 수 있습니다 xcountdown()을 실행하는 데 lambda를 사용합니다. BTW

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() 

(당신이 int를 사용할 때 당신은 첫 번째 예에서 동일한 작업을 수행 할 수 없음) : 당신은 :)

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() 
0

http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/control-variables.html의 "버튼"섹션에서 설명한 것처럼 버튼을 동적으로 업데이트하려면 StringVar 특수 문자를 만들어야합니다. StringVarButton 생성자 변수 textvariable에 전달하고 countdown() 함수 내에서 StringVar 값을 업데이트 할 수 있습니다. http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/button.htmltextvariable

이 단추의 텍스트와 연결된 인스턴스입니다. 변수가 변경되면 새 값이 버튼에 표시됩니다.

+0

'StringVar()'는 이것에 대한 과잉 사용입니다. 'B.config (text = ..)'할 수 있습니다. – Lafexlos

관련 문제