Canvas 画布组件
- 1、一个经典的面向程序写法模块
- 2、画布组件(Canvas)
- 3、随机画 10 个矩形
- 4、源代码
1、一个经典的面向程序写法模块
from tkinter import *
from tkinter import messagebox
class Appication(Frame):
"""
一个经典的 GUI 类的写法
"""
def __init__(self, master = None):
super().__init__(master)
self.master = master
self.pack()
self.CreateWidget()
def CreateWidget(self):
"""
用途:创建组件
"""
......
......
if __name__ == "__main__":
window = Tk()
window.geometry("500x200+200+200")
window.title('一个经典的GUI程序')
app = Appication(master = window)
window.mainloop()
2、画布组件(Canvas)
def CreateWidget(self):
"""
用途:创建组件
"""
self.canvas = Canvas(self, width = 300, height = 300, bg = "green")
self.canvas.pack()
line = self.canvas.create_line(10, 10, 20, 20, 30, 30, 40, 90)
rect = self.canvas.create_rectangle(10, 10, 100, 100)
oval = self.canvas.create_oval(10, 10, 100, 100)
global photo
photo = PhotoImage(file = "image\\xiaohan.gif")
self.canvas.create_image(200, 200, image = photo)
3、随机画 10 个矩形
def CreateWidget(self):
"""
用途:创建组件
"""
Button(self, text = "画 10 个矩形", command = self.draw10Rectangle).pack(side = "left")
def draw10Rectangle(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["width"] / 2))
y2 = y1 + random.randrange(int(self.canvas["height"] / 2))
self.canvas.create_rectangle(x1, y1, x2, y2)
4、源代码
from tkinter import *
from tkinter import messagebox
import random
class Appication(Frame):
"""
一个经典的 GUI 类的写法
"""
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 = 300, bg = "green")
self.canvas.pack()
line = self.canvas.create_line(10, 10, 20, 20, 30, 30, 40, 90)
rect = self.canvas.create_rectangle(10, 10, 100, 100)
oval = self.canvas.create_oval(10, 10, 100, 100)
global photo
photo = PhotoImage(file = "image\\xiaohan.gif")
self.canvas.create_image(200, 200, image = photo)
Button(self, text = "画 10 个矩形", command = self.draw10Rectangle).pack(side = "left")
def draw10Rectangle(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["width"]) / 2)
y2 = y1 + random.randrange(int(self.canvas["height"]) / 2)
self.canvas.create_rectangle(x1, y1, x2, y2)
if __name__ == "__main__":
window = Tk()
window.geometry("600x600+100+100")
window.title('一个经典的GUI程序')
app = Appication(master = window)
window.mainloop()