英文:
How to draw smooth looking lines on Tkinter
问题
以下是代码部分的翻译:
import tkinter as tk
class DrawingApp:
def __init__(self, master):
self.master = master
self.canvas = tk.Canvas(self.master, width=1024, height=256)
self.canvas.pack()
self.previous_coordinates = None
self.canvas.bind("<B1-Motion>", self.draw)
self.canvas.bind("<Button-3>", self.erase)
self.canvas.bind("<Button-1>", self.draw)
self.canvas.bind("<ButtonRelease-1>", self.reset)
def draw(self, event):
if self.previous_coordinates:
x1, y1 = self.previous_coordinates
x2, y2 = event.x, event.y
self.canvas.create_line(x1, y1, x2, y2, fill="black", width=20, capstyle=tk.PROJECTING,
joinstyle=tk.BEVEL, smooth=True, splinesteps=36)
self.previous_coordinates = (event.x, event.y)
def erase(self, event):
# 删除画布上的所有绘图
self.canvas.delete("all")
def reset(self, event):
self.previous_coordinates = None
root = tk.Tk()
app = DrawingApp(root)
root.mainloop()
希望这有所帮助。如果您有其他问题,可以继续提问。
英文:
I want to make a simple drawing app using Tkinter, I want to draw lines using my mouse, the solution that I came up with works fine, and I can even draw multiple lines but in the picture below you can see that lines look jagged. My question is can I draw smooth looking lines on Tkinter?
Here is the code that I am using to draw lines on the canvas:
import tkinter as tk
class DrawingApp:
def __init__(self, master):
self.master = master
self.canvas = tk.Canvas(self.master, width=1024, height=256)
self.canvas.pack()
self.previous_coordinates = None
self.canvas.bind("<B1-Motion>", self.draw)
self.canvas.bind("<Button-3>", self.erase)
self.canvas.bind("<Button-1>", self.draw)
self.canvas.bind("<ButtonRelease-1>", self.reset)
def draw(self, event):
if self.previous_coordinates:
x1, y1 = self.previous_coordinates
x2, y2 = event.x, event.y
self.canvas.create_line(x1, y1, x2, y2, fill="black", width=20, capstyle=tk.PROJECTING,
joinstyle=tk.BEVEL, smooth=True, splinesteps=36)
self.previous_coordinates = (event.x, event.y)
def erase(self, event):
# delete every drawing in the canvas
self.canvas.delete("all")
def reset(self, event):
self.previous_coordinates = None
root = tk.Tk()
app = DrawingApp(root)
root.mainloop()
答案1
得分: 0
尝试将capstyle
选项更改为tk.ROUND
,可能会提高平滑度。
还要注意,smooth
和splinesteps
选项对于两点之间的直线无效。
self.canvas.create_line(x1, y1, x2, y2, fill="black", width=20,
capstyle=tk.ROUND, joinstyle=tk.BEVEL)
结果:
英文:
Try changing capstyle
option to tk.ROUND
and it may improve the smoothness a bit.
Note also that smooth
and splinesteps
options are useless of a straight line between two points.
self.canvas.create_line(x1, y1, x2, y2, fill="black", width=20,
capstyle=tk.ROUND, joinstyle=tk.BEVEL)
Result:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论