2016-01-30 43 views
2

我想用Tkinter创建一个简单的表单,一旦按下按钮就会执行一个动作。我如何“听”按钮按?tkraise之后循环?

我已经创建了一个回调方法,它将在按下按钮时更改状态变量,但在按下按钮时无法弄清楚如何在主循环中产生动作。我试图使用while循环(绘制按钮后)检查状态变量的值,但是当我这样做时,循环执行,但我的GUI元素不出现在屏幕上。 (如果我使用for循环,它们确实会出现,但我认为这不会起作用)。

如何“等待”状态更改为“状态”变量?还是有一种内置的方式来做到这一点,我失踪了?

(实际的代码稍微复杂一点 - 类似于回答here的方法(但没有所有的按钮都在一个页面上) - 但我认为原理还是一样的(如何聆听变化在状态对象变量之一)。)

from Tkinter import * 

master = Tk() 

def callback(): 
    status = 0 
    print status 

status = 1 

myB = Button(text="Enter", command=callback) 
myB.pack() 
print status 

# while True: 
# if status == 0: 
#  print "button was clicked" 

mainloop() 
+2

'主循环()'启动程序并运行,直到你关闭程序。您不能在Tkinter(或其他GUI)中使用'while循环','睡眠'或其他长时间运行的函数。 – furas

+0

@furas - 谢谢。 是否有另一种方法来“聆听”变量的变化? – user3092118

+0

您可以使用'tkinter.IntVar'来创建特殊的对象变量a,然后使用'trace'在该对象更改值时调用函数。 – furas

回答

3

您可以使用after(time_ms, function_name)反复(但不while True)调用你的函数。

import Tkinter as tk 

# --- functions --- 

def check(): 
    if status != 1: 
     print 'check:', status 

    # check again after 100ms 
    master.after(100, check) # filename without() 

def callback(): 
    global status # because you use `=` 

    status = 0 

    print 'callback:', status 

# --- main --- 

status = 1 

master = tk.Tk() 

myB = tk.Button(master, text="Enter", command=callback) 
myB.pack() 

# check after 100ms 
master.after(100, check) # filename without() 
# or call immediately 
# check() 

tk.mainloop() 

或者您可以使用对象IntVarStringVar等,trace调用函数时,对象的变化值。

此外,Label可以在StringVar更改值时自动更改文本 - 它不需要trace

import Tkinter as tk 

# --- functions --- 

def check(arg1, arg2, arg3): # 3 args always send by `trace` 
    print 'check:', status.get() # always use `get` 

def callback(): 
    # no needed `global status` 

    status.set(0) # always use `set` instead of `=` 

    print 'callback:', status.get() # always use `get` 

# --- main --- 

master = tk.Tk() 

status = tk.IntVar() # now always use get(), set() 
status.set(1) 

status.trace('w', check) # w - write (`set` was used) 

# use IntVar in Label 
l = tk.Label(master, textvariable=status) 
l.pack() 

b = tk.Button(master, text="Enter", command=callback) 
b.pack() 

tk.mainloop() 

见:The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar)