[英]<B1-Motion> binding is unresponsive in Tkinter
我一直致力於在 tkinter 中學習更多關於Canvas()
小部件的信息,因此我決定構建一個簡單的繪畫應用程序以供練習。
為此,我創建了一個 canvas 並將其綁定到"<B1-Motion>"
,但是當我拖動鼠標太快時它變得無響應。
這是一個代碼示例:
from tkinter import *
class Paint:
def __init__(self, root):
self.root = root
self.current_x = None
self.current_y = None
self.brush_size = 10
self.brush_color = "black"
def create_widgets(self):
# Creating the canvas
self.canvas = Canvas(self.root, width=1000, height=1000)
self.canvas.grid(row=0, column=0, sticky="nsew")
# Setting up bindings for the canvas.
self.canvas.bind("<Button-1>", self.setup_coords)
self.canvas.bind("<B1-Motion>", self.drag)
def setup_coords(self, e):
# Reset the starting points to the current mouse position
self.current_x = e.x
self.current_y = e.y
def drag(self, e):
# Create an oval that's size is the same as brush_size
oval = self.canvas.create_oval(self.current_x, self.current_y, self.current_x+self.brush_size, self.current_y+self.brush_size, fill=self.brush_color)
# Set the variables values to the current position of the mouse, so that the oval gets drawn correctly on the next call.
self.current_x = e.x
self.current_y = e.y
def main():
root = Tk()
root.geometry("1000x1000")
p = Paint(root)
p.create_widgets()
mainloop()
if __name__ == '__main__':
main()
但是,一旦我開始快速拖動,就不會按時調用綁定,只會繪制幾個圓圈:
我在這里做事效率低下嗎? 有什么辦法可以解決這個問題嗎?
如果有人能幫助我,那就太好了。 提前致謝。
更新:
我嘗試了 acw1668 的建議,即畫線而不是圓並將其寬度設置為畫筆大小:
from tkinter import *
class Paint:
def __init__(self, root):
self.root = root
self.current_x = None
self.current_y = None
self.brush_size = 50
self.brush_color = "black"
def create_widgets(self):
# Creating the canvas
self.canvas = Canvas(self.root, width=1000, height=1000)
self.canvas.grid(row=0, column=0, sticky="nsew")
# Setting up bindings for the canvas.
self.canvas.bind("<Button-1>", self.setup_coords)
self.canvas.bind("<B1-Motion>", self.drag)
def setup_coords(self, e):
# Reset the starting points to the current mouse position
self.current_x = e.x
self.current_y = e.y
def drag(self, e):
# Create an oval that's size is the same as brush_size
oval = self.canvas.create_line(self.current_x, self.current_y, e.x, e.y, width=self.brush_size, fill=self.brush_color)
# Set the variables values to the current position of the mouse, so that the oval gets drawn correctly on the next call.
self.current_x = e.x
self.current_y = e.y
def main():
root = Tk()
root.geometry("1000x1000")
p = Paint(root)
p.create_widgets()
mainloop()
if __name__ == '__main__':
main()
任何修復?
對於連接良好的線條,在創建線條時將 set capstyle
設置為round
。
查看此 canvas 教程了解更多詳情。
我熟悉的幾乎所有繪圖庫都支持不同的線端(“caps”)styles,以及線連接(“joins”)styles。
另請注意,您可以使用create_line
繪制二次貝塞爾樣條曲線或三次樣條曲線。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.