下面是通过单击拖动和释放绘制矩形的代码...由于某些原因它不起作用,画布屏幕显示但矩形不被绘制?它是root.mainloop()行吗?因为我改变它是因为我需要绘制弧线和线条而且不能只有app = rectangle和app.mainloop ...对不起,我真的很陌生。
from tkinter import Canvas, Tk, mainloop
import tkinter as tk
from PIL import Image, ImageTk
# Image dimensions
w,h = 800,400
# Create canvas
root = Tk()
canvas = Canvas(root, width = w, height = h, bg='#D2B48C', cursor = "cross")
canvas.pack()
class Rectangle(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.x = self.y = 0
self.canvas.pack(side="top", fill = "both", expand = True)
self.canvas.bind("<ButtonPress-1>", self.press)
self.canvas.bind("<B1-Motion>", self.move)
self.canvas.bind("<ButtonRelease-1>", self.release)
self.rect = None
self.start_x = None
self.start_y = None
def press(self, event):
# save mouse drag start position
self.start_x = event.x
self.start_y = event.y
self.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, fill="red")
def move(self, event):
mouseX, mouseY = (event.x, event.y)
# expand rectangle as you drag the mouse
self.canvas.coords(self.rect, self.start_x, self.start_y, mouseX, mouseY)
def release(self, event):
pass
# Other Classes for arc and pencil begin here
root.mainloop()
谢谢大家!!!
答案 0 :(得分:1)
作为 @BryanOakley 评论,提供的来源包含未完成的分析,并揭示了对tkinter使用的误解。
问题1 - class Rectangle
不需要继承tk.Tk
。
不是从
class Rectangle
继承tk.Tk
,而是添加。{ 实例创建时Canvas
实例。
class Rectangle(): # not inherit from ==> tk.Tk):
def __init__(self,canvas):
# not initialize a second Tk instance ==> tk.Tk.__init__(self)
self.x = self.y = 0
# attach the main canvas
self.canvas = canvas
self.canvas.pack(side="top", fill = "both", expand = True)
而不是:
class Rectangle(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.x = self.y = 0
self.canvas.pack(side="top", fill = "both", expand = True)
问题2 - 尚未创建class Rectangle
的实例。
要使用
class Rectangle
,应创建一个实例 附加到canvas
实例!!之前,在
Tk()
和Canvas()
之前移动课程声明 创建
class Rectangle(tk.Tk):
def __init__(self):
...
def release(self, event):
pass
# Other Classes for arc and pencil begin here
root = Tk()
canvas = Canvas(root, width = w, height = h, bg='#D2B48C', cursor = "cross")
canvas.pack()
# create the Rectangle instance
hRect = Rectangle(canvas)
root.mainloop()
而不是:
root = Tk()
canvas = Canvas(root, width = w, height = h, bg='#D2B48C', cursor = "cross")
canvas.pack()
class Rectangle(tk.Tk):
def __init__(self):
...
def release(self, event):
pass
# Other Classes for arc and pencil begin here
root.mainloop()
答案 1 :(得分:0)
首先,你永远不会创建Rectangle
类的实例,这是你所有逻辑的所在。
另一方面,您只能拥有Tk
的单个实例。您可以在问题开始时创建一个,然后在创建Rectangle
实例时再创建另一个。同样,你只能有一个。