我有一个 Tkinter 画布小部件,我想在它上面创建一个点画图案。我知道我可以使用create_line方法手动完成。但是,我认为似乎有更好的方法。任何帮助将非常感激。
我目前正在使用的东西。(按 Alt-F4 退出程序)
import Tkinter, re
class StippleCanvas(Tkinter.Tk):
def __init__(self, parent):
Tkinter.Tk.__init__(self, parent)
self.overrideredirect(1)
self.resizable(False,False)
self.wm_attributes("-topmost", 1)
self.attributes("-alpha", 0.9)
w = 90
h = 90
self.Ca = Tkinter.Canvas(self, width=w, height=h, highlightthickness=0, bd=0, bg='grey25')
self.Ca.grid(column=0, row=0)
self.bind('<Button-1>', self.relative_mouse_position)
self.bind('<ButtonRelease-1>', self.wid_unbind)
i0 = 0
while i0 < w:
i1 = 0
while i1 < h:
self.Ca.create_line(i1, i0, i1+1, i0, fill='grey20', width=1)
i1 = i1 + 2
i0 = i0 + 2
def geom_grab (self):
Cursorgfltr = re.compile(r"(\d+), (\d+)")
CursorPos = self.winfo_pointerxy()
CursorPosGr = Cursorgfltr.search(str(CursorPos))
self.CursorX = int(CursorPosGr.group(1))
self.CursorY = int(CursorPosGr.group(2))
gfltr = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
gf = gfltr.search(self.wm_geometry())
self.X = int(gf.group(4))
self.Y = int(gf.group(6))
def relative_mouse_position (self, event):
self.geom_grab()
RelX = self.CursorX - self.X
RelY = self.CursorY - self.Y
self.Ca.bind( "<Motion>", lambda event: self.wid_drag(event, RelX, RelY) )
def wid_drag (self, event, RelX, RelY):
self.geom_grab()
X = self.CursorX - RelX
Y = self.CursorY - RelY
if X < 0:
X = 0
if Y < 0:
Y = 0
self.wm_geometry('+' + str(X) + '+' + str(Y))
def wid_unbind (self, event):
self.Ca.unbind("<Motion>")
def run():
StippleCanvas(None).mainloop()
if __name__ == '__main__':
run()