Tkinter
Tkinter是Python的一款功能强大且全面、操作简易的GUI编程模块。今天,我们将使用tkinter制作一款简易画图软件。加油吧!
最终效果如下:
下载模块
我们将使用Python 3.10为编译器,使用 pip 下载所需模块:
pip install tkinter
pip install PIL
导入模块
这里,我们将导入所有所需的模块。
import time
import tkinter
import tkinter.simpledialog
import tkinter.colorchooser
import tkinter.filedialog
from PIL import Image, ImageTk, ImageGrab
设置主窗口
设置所有接下来所需的元素,并初始化。
def center_window(w, h):
app.winfo_screenwidth()
app.winfo_screenheight()
app.geometry('%dx%d' % (w, h))
app = tkinter.Tk()
app.title('轩氏画图')
x = 1200
y = 800
center_window(x, y)
yesno = tkinter.IntVar(value=0)
what = tkinter.IntVar(value=1)
X = tkinter.IntVar(value=0)
Y = tkinter.IntVar(value=0)
foreColor = '#000000'
backColor = '#FFFFFF'
image = tkinter.PhotoImage()
canvas = tkinter.Canvas(app, bg='white', width=x, height=y)
canvas.create_image(x, y, image=image)
lastDraw = 0
end = [0]
size = "20"
基本画图运算逻辑
重点来了!我们使用鼠标左键按下等动作探测,绘制曲线:
def getter(widget):
time.sleep(0.5)
x = app.winfo_x() + widget.winfo_x()
y = app.winfo_y() + widget.winfo_y()
if app.winfo_x() < 0:
x = 0
if app.winfo_y() < 0:
y = 0
x1 = x + widget.winfo_width() + 200
y1 = y + widget.winfo_height() + 200
filename = tkinter.filedialog.asksaveasfilename(filetypes=[('.jpg', 'JPG')],
initialdir='C:\\Users\\lin042\\Desktop\\')
ImageGrab.grab().crop((x, y, x1, y1)).save(filename)
def onLeftButtonDown(event):
yesno.set(1)
X.set(event.x)
Y.set(event.y)
if what.get() == 4:
canvas.create_text(event.x, event.y, font=("等线", int(size)), text=text, fill=foreColor)
what.set(1)
def onLeftButtonMove(event):
global lastDraw
if yesno.get() == 0:
return
if what.get() == 1:
lastDraw = canvas.create_line(X.get(), Y.get(), event.x, event.y,
fill=foreColor)
X.set(event.x)
Y.set(event.y)
elif what.get() == 2:
try:
canvas.delete(lastDraw)
except Exception:
pass
lastDraw = canvas.create_line(X.get(), Y.get(), event.x, event.y,
fill=foreCol