2016-10-14 8 views
0

ボタンが1つしかない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

なぜその編集を元に戻したのですか?信じられないほど明白ではありませんでしたか? – jonrsharpe

+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を必要としません。私は、私は別のIntVarで多くのボタンでcountdownを使用することができますxcountdown()を実行するためにlambdaを使用

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

。ところで

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を使用するときは、最初の例では同じことを行うことはできません):あなたはクリックせず、すべて1とカウントダウン機能countdownを実行するためにafter(miliseconds, functio_name)を使用することができます:)

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

関連する問題