Reputation: 2456
By modifying some code that was present in one of the answers in Stackoverflow (sorry, i don't remember which one it is exactly), here is the code snippet.
I was trying to improve on it by using the 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'
I'm trying to get the values and return it to the rest of the mainloop in real time. How do we achieve that?
Upvotes: 2
Views: 5700
Reputation: 369274
Instead of using thread, use callback (specify using command
keyword arugment)
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()
The callback is called when the value of the scale is changed.
UPDATE
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
Upvotes: 3