用Python实现一个刻度尺
时间: 2023-11-05 22:02:31 浏览: 104
由于题目没有明确指定刻度尺的样式和功能,因此我做了一个简单的刻度尺,可以设置最小值、最大值、刻度间隔和初始值,并且可以通过滑动滑块来改变初始值。
具体实现如下:
```python
import tkinter as tk
class Scale(tk.Frame):
def __init__(self, master=None, **kw):
super().__init__(master, **kw)
self.min_value = kw.get('min_value', 0)
self.max_value = kw.get('max_value', 100)
self.interval = kw.get('interval', 10)
self.value = kw.get('value', self.min_value)
self.create_widgets()
def create_widgets(self):
self.canvas = tk.Canvas(self, width=400, height=50)
self.canvas.pack(side='top', fill='both', expand=True)
self.create_scale()
self.create_slider()
def create_scale(self):
x0, x1, y = 30, 370, 25
interval_num = int((self.max_value - self.min_value) / self.interval) + 1
for i in range(interval_num):
x = x0 + (x1 - x0) * i / (interval_num - 1)
self.canvas.create_line(x, y-10, x, y+10)
self.canvas.create_text(x, y+15, text=str(self.min_value+i*self.interval))
self.canvas.create_line(x0, y, x1, y, width=2)
def create_slider(self):
x0, x1, y = 20, 380, 35
self.slider = self.canvas.create_line(x0, y, x1, y, fill='red', width=2)
self.slider_handle = self.canvas.create_rectangle(x0-5, y-10, x0+5, y+10, fill='white', outline='black')
self.canvas.tag_bind(self.slider_handle, '<Button-1>', self.on_slider_pressed)
self.canvas.tag_bind(self.slider_handle, '<B1-Motion>', self.on_slider_dragged)
def on_slider_pressed(self, event):
self.slider_offset = event.x - self.canvas.coords(self.slider_handle)[0]
def on_slider_dragged(self, event):
x = event.x - self.slider_offset
x0, x1 = 20, 380
x = max(x, x0)
x = min(x, x1)
self.canvas.coords(self.slider_handle, x-5, 25, x+5, 45)
value_range = self.max_value - self.min_value
interval_num = int(value_range / self.interval)
value = self.min_value + int((x-x0) * value_range / (x1-x0) / self.interval) * self.interval
self.value = value
self.canvas.coords(self.slider, x0, 35, x, 35)
def get(self):
return self.value
if __name__ == '__main__':
root = tk.Tk()
root.geometry('400x100')
root.title('Scale')
scale = Scale(root, min_value=0, max_value=100, interval=10, value=50)
scale.pack(side='top', fill='both', expand=True)
def print_value():
print(scale.get())
button = tk.Button(root, text='Print', command=print_value)
button.pack(side='bottom')
root.mainloop()
```
这个刻度尺的样式比较简单,只是一条线和一个滑块,但是可以通过设置最小值、最大值、刻度间隔和初始值来满足不同的需求。同时,滑块也可以随意拖动,实现了改变初始值的功能。在使用时,只需要实例化一个Scale对象,并将其放入窗口中即可。通过调用get()方法可以获取当前刻度尺的值。
阅读全文