2

通过修改 Stackoverflow 中的一个答案中存在的一些代码(对不起,我不记得它到底是哪一个),这里是代码片段。我试图通过使用tkinter scale.

#!/usr/bin/env python

from Tkinter import *
import threading

class MyTkApp(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.start()
    def callback(self):
       self.root.quit()
    def show_values(self):
       print self.s2.get()
       print self.s1.get()
    def run(self):
        self.root=Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback)
        self.s1 = Scale(self.root, from_=0, to=42, tickinterval=8)
    self.s1.set(19)
    self.s1.pack()
    self.s1.get()
    self.s2 = Scale(self.root, from_=0, to=200, length=600,tickinterval=10, orient=HORIZONTAL)
    self.s2.set(23)
    self.s2.pack()
    Button(self.root, text='Show', command=self.show_values).pack()
    self.root.mainloop()

app = MyTkApp()
print app.show_values()    
for a in range(0,10):
    print 'now can continue running code while mainloop runs'

我正在尝试获取这些值并将其实时返回到主循环的其余部分。我们如何做到这一点?

4

1 回答 1

1

不使用线程,而是使用回调(使用command关键字参数指定)

from Tkinter import *

def show_values(value=None):
    print s1.get(), s2.get()

root=Tk()
s1 = Scale(root, from_=0, to=42, tickinterval=8, command=show_values)
#                                                ^^^^^^^^^^^^^^^^^^^
s1.set(19)
s1.pack()
s2 = Scale(root, from_=0, to=200, length=600, tickinterval=10, orient=HORIZONTAL,
           command=show_values) # <---
s2.set(23)
s2.pack()
Button(root, text='Show', command=show_values).pack()
root.mainloop()

当比例尺的值改变时调用回调。


更新

from Tkinter import *
import time
import threading

class ScaleValue:
    def __init__(self):
        self.value1 = None
        self.value2 = None

def tkinter_loop(scale):
    root=Tk()
    s1 = Scale(root, from_=0, to=42, tickinterval=8, command=lambda v: setattr(scale, 'value1', v))
    s1.set(19)
    s1.pack()
    s2 = Scale(root, from_=0, to=200, length=600, tickinterval=10, orient=HORIZONTAL, command=lambda v: setattr(scale, 'value2', v))
    s2.set(23)
    s2.pack()
    root.mainloop()

scale = ScaleValue()
threading.Thread(target=tkinter_loop, args=(scale,)).start()

# ROP
while 1:
    time.sleep(1)
    print scale.value1, scale.value2
于 2013-10-23T07:00:32.237 回答