"""使用面向对象的方式写GUI""" import random """Write GUI in an object-oriented manner""" from tkinter import * class Application(Frame): def __init__(self,master=None): super().__init__(master) self.master = master self.pack() self.createWidget() def createWidget(self): self.canvas = Canvas(self, width=300, height=200, bg="green") self.canvas.pack() # 画一条直线 Draw a straight line line = self.canvas.create_line(10, 10, 30, 20, 40, 50) # 画一个矩形 Draw a rectangle rect = self.canvas.create_rectangle(50, 50, 100, 100) # 画一个椭圆,两对坐标为椭圆的边界矩形左上角和底部右下角 # Draw an ellipse with two pairs of coordinates for the upper # left corner and the lower right corner of the boundary rectangle oval = self.canvas.create_oval(50, 50, 100, 100) global photo photo = PhotoImage(file="image/123.gif") self.canvas.create_image(150, 170, image=photo) Button(self, text="Draw ten rectangle", command=self.draw50Recg).pack(side="left") # 画十个圆的方法 def draw50Recg(self): for i in range(0, 10): x1 = random.randrange(int(self.canvas["width"])/2) y1 = random.randrange(int(self.canvas["height"])/2) x2 = x1 + random.randrange(int(self.canvas["height"])/2) y2 = y1 + random.randrange(int(self.canvas["height"])/2) self.canvas.create_rectangle(x1, y1, x2, y2) if __name__ == '__main__': root = Tk() root.geometry("400x300+200+300") app = Application(master=root) root.title('Test for canvas') root.mainloop()
python GUI canvas 编写
于 2023-04-07 17:29:03 首次发布
该代码示例展示了如何使用Python的tkinter库以面向对象的方式创建一个简单的图形用户界面。它包括创建Canvas,绘制直线、矩形、椭圆以及从文件加载图像。此外,还有一个按钮功能,点击后会在Canvas上随机位置绘制多个矩形。
摘要由CSDN通过智能技术生成