[Tutor] how can a value be retrieved from an event loop?
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Nov 16 08:45:57 EST 2023
On 16/11/2023 11:35, Phil wrote:
> What I'm trying to do is create a knob that works in the same fashion as
> the scale widget.
OK, I took your code and tweaked it to do what I think you want.
Note that you now set the initial angle by passing it to the
constructor call.
Also note that the angle is in radians so if you want to use
degrees you will need to do a bit of math inside the code.
=============
import tkinter as tk
import math
class KNOB(tk.Canvas):
def __init__(
self,
parent,
size=100,
angle=0
):
super().__init__(parent, width=size, height=size)
self.size = size
self.color1 = "#007DC8"
self.color2 = "#98D2D2"
self.angle = angle
self.border = self.create_oval(
0.1 * size,
0.1 * size,
0.9 * size,
0.9 * size,
outline=self.color1,
width=3,
fill=self.color2,
)
self.dot = None # make a "dot" for first draw_dot to remove!
self.draw_dot()
self.bind("<Button-3>", self.turn_clockwise)
self.bind("<Button-1>", self.turn_counterwise)
def draw_dot(self):
self.delete(self.dot)
centerX = 0.5 * self.size + (0.25 * self.size *
math.sin(self.angle))
centerY = 0.5 * self.size - (0.25 * self.size *
math.cos(self.angle))
self.dot = self.create_oval(
(centerX - 0.05 * self.size),
(centerY - 0.05 * self.size),
(centerX + 0.05 * self.size),
(centerY + 0.05 * self.size),
outline=self.color1,
width=3,
)
def turn_clockwise(self, event):
self.angle = self.angle + 0.1
self.draw_dot()
self.get_angle()
def turn_counterwise(self, event):
self.angle = self.angle - 0.1
self.draw_dot()
self.get_angle()
def get_angle(self):
print(self.angle)
return self.angle
def set_angle(self, angle):
self.angle = angle
self.get_angle()
if __name__ == "__main__":
root = tk.Tk()
root.title("Knob test")
knob = KNOB(root, angle=15)
knob.pack(padx=20, pady=20)
root.mainloop()
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list