Python: TKinter - работа с графикой
Полезный материал:
- Tkinter. Программирование GUI на Python. Курс.
- Tkinter - создание графического интерфейса в Python.
- Tkinter. Рисование в Tkinter [Урок №6].
- Tkinter. Обучение Python GUI (уроки по Tkinter).
Рисуем координатную плоскость и график синуса:
import tkinter
import math
WINWIDTH = 600
def f(x):
return 10 * math.sin(x / 10)
master = tkinter.Tk()
canvas = tkinter.Canvas(master, bg='white', height=600, width=WINWIDTH)
canvas.create_line((0, 0), (WINWIDTH, 600), fill='red')
ox = 300
oy = 300
xn = -100
xk = 100 # {интервал по Х}
mx = (WINWIDTH - ox - 30) / xk # {масштаб по Х}
my = (oy - 40) / 10 # {по У}
dots = []
canvas.create_line((0, oy), (WINWIDTH, oy), fill='black') # {оси}
canvas.create_line((ox, 0), (ox, WINWIDTH), fill='black')
for i in range(1, 11): # {максимальное количество засечек в одну сторону}
canvas.create_line((ox + round(i * mx * 10), oy - 3),
(ox + round(i * mx * 10), oy + 3),
fill="black") # {засечки на оси Х}
canvas.create_line((ox - round(i * mx * 10), oy - 3),
(ox - round(i * mx * 10), oy + 3),
fill="black")
canvas.create_line((ox + 3, oy - round(i * my)),
(ox - 3, oy - round(i * my)),
fill='black') # {засечки на оси Y}
canvas.create_line((ox + 3, oy + round(i * my)),
(ox - 3, oy + round(i * my)),
fill='black')
x = xn
dx = 0.001
while x <= xk:
x = x + dx # {наращиваем х}
dots.append((ox + round(x * mx), oy - round(f(x) * my)))
canvas.create_line(dots, fill='blue')
canvas.pack()
master.mainloop()
Управляем окружностью с клавиатуры:
import tkinter
def key_pressed(event):
if event.keysym == 'space':
canvas.coords(oval, (300, 300, 310, 310))
if event.keysym == 'Up':
canvas.move(oval, 0, -10)
elif event.keysym == 'Down':
canvas.move(oval, 0, 10)
elif event.keysym == 'Left':
canvas.move(oval, -10, 0)
elif event.keysym == 'Right':
canvas.move(oval, 10, 0)
if canvas.coords(oval)[1] < 50: # координата y1
canvas.itemconfig(oval, fill='red')
if canvas.coords(oval)[0] < 50: # координата x1
canvas.move(oval, 400, 0)
master = tkinter.Tk()
canvas = tkinter.Canvas(master, bg='blue', height=600, width=600)
oval = canvas.create_oval((100, 100), (210, 210), fill='green')
fringe = canvas.create_line((50, 0), (50, 600), fill='white', width=3)
canvas.pack()
master.bind("<KeyPress>", key_pressed)
master.mainloop()
Координатная плоскость с масштабом:
import tkinter
import math
WINWIDTH = 600
WINHEIGHT = 600
master = tkinter.Tk()
canvas = tkinter.Canvas(master, bg='white', height=WINHEIGHT, width=WINWIDTH)
#canvas.create_line((0, 0), (WINWIDTH, WINHEIGHT), fill='red')
ox = 50
oy = 300
mx = 30 # {масштаб по Х}
my = 30 # {по У}
h = 4
ht = 14
dots = []
canvas.create_line((0, oy), (WINWIDTH, oy), fill='black') # {оси}
canvas.create_line((ox, 0), (ox, WINWIDTH), fill='black')
for i in range(1, 11): # {максимальное количество засечек в одну сторону}
canvas.create_line((ox + round(i * mx), oy - h),
(ox + round(i * mx), oy + h),
fill="red") # {засечки на оси Х}
canvas.create_line((ox - round(i * mx), oy - h),
(ox - round(i * mx), oy + h),
fill="red")
canvas.create_text(ox - round(i * mx), oy + ht, text=str(i * -mx));
canvas.create_text(ox + round(i * mx), oy + ht, text=str(i * mx));
canvas.create_line((ox + h, oy - round(i * my)),
(ox - h, oy - round(i * my)),
fill='green') # {засечки на оси Y}
canvas.create_line((ox + h, oy + round(i * my)),
(ox - h, oy + round(i * my)),
fill='green')
canvas.create_text(ox + ht, oy - round(i * my), text=str(i * -my));
canvas.create_text(ox + ht, oy + round(i * my), text=str(i * my));
canvas.pack()
master.mainloop()
Координатная плоскость с масштабом + КНОПКИ:
import tkinter
import math
def lines():
canvas.create_line((0, oy), (WINWIDTH, oy), fill='black') # {оси}
canvas.create_line((ox, 0), (ox, WINWIDTH), fill='black')
def coords():
for i in range(1, 11): # {максимальное количество засечек в одну сторону}
canvas.create_line((ox + round(i * mx), oy - h),
(ox + round(i * mx), oy + h),
fill="red") # {засечки на оси Х}
canvas.create_line((ox - round(i * mx), oy - h),
(ox - round(i * mx), oy + h),
fill="red")
canvas.create_line((ox + h, oy - round(i * my)),
(ox - h, oy - round(i * my)),
fill='green') # {засечки на оси Y}
canvas.create_line((ox + h, oy + round(i * my)),
(ox - h, oy + round(i * my)),
fill='green')
def texts():
for i in range(1, 11): # {максимальное количество засечек в одну сторону}
canvas.create_text(ox - round(i * mx), oy + ht, text=str(i * -mx));
canvas.create_text(ox + round(i * mx), oy + ht, text=str(i * mx));
canvas.create_text(ox + ht, oy - round(i * my), text=str(i * -my));
canvas.create_text(ox + ht, oy + round(i * my), text=str(i * my));
WINWIDTH = 600
WINHEIGHT = 600
master = tkinter.Tk()
canvas = tkinter.Canvas(master, bg='white', height=WINHEIGHT, width=WINWIDTH)
tkinter.Button(master, text='Закрыть', command=master.destroy).pack()
tkinter.Button(master, text='Линии', command=lines).pack()
tkinter.Button(master, text='Координаты', command=coords).pack()
tkinter.Button(master, text='Надписи', command=texts).pack()
ox = 50
oy = 300
mx = 30 # {масштаб по Х}
my = 30 # {по У}
h = 4
ht = 14
dots = []
canvas.pack()
master.mainloop()
Координатная плоскость с графиком (масштабирование 1):
import tkinter
import math
def F(x):
return x ** 3
WINWIDTH = 600
WINHEIGHT = 400
ox = 100
oy = 200
master = tkinter.Tk()
canvas = tkinter.Canvas(master, bg='white', height=WINHEIGHT, width=WINWIDTH)
#canvas.create_line((0, 0), (WINWIDTH, WINHEIGHT), fill='red')
li = []
x1 = -10
x2 = 50
minx = x1
maxx = x2
while x1 <= x2:
x1 += 1
li.append((x1, F(x1)))
miny = min([x[1] for x in li])
maxy = max([x[1] for x in li])
dx = maxx - minx
dy = maxy - miny
# mx = 30 # {масштаб по Х}
# my = 30 # {по У}
if ox > (WINWIDTH // 2):
mx = ox // dx # {по X}
else:
mx = (WINWIDTH - ox) // dx # {масштаб по Х}
if oy > (WINHEIGHT // 2):
my = oy // dy # {по У}
else:
my = (WINHEIGHT - oy) // dy # {по У}
if mx == 0:
mx = 1
if my == 0:
my = 1
h = 4
ht = 14
#mx = 45
#my = 4
dots = []
for x, y in li:
dots.append((ox + x * mx, oy - y * my))
print(mx, my, dy, li)
print(dots)
canvas.create_line(dots, fill='blue') # {график функции}
canvas.create_line((0, oy), (WINWIDTH, oy), fill='black') # {оси}
canvas.create_line((ox, 0), (ox, WINWIDTH), fill='black')
for i in range(1, 11): # {максимальное количество засечек в одну сторону}
canvas.create_line((ox + round(i * mx), oy - h),
(ox + round(i * mx), oy + h),
fill="red") # {засечки на оси Х}
canvas.create_line((ox - round(i * mx), oy - h),
(ox - round(i * mx), oy + h),
fill="red")
canvas.create_text(ox - round(i * mx), oy + ht, text=str(i * -mx))
canvas.create_text(ox + round(i * mx), oy + ht, text=str(i * mx))
canvas.create_line((ox + h, oy - round(i * my)),
(ox - h, oy - round(i * my)),
fill='green') # {засечки на оси Y}
canvas.create_line((ox + h, oy + round(i * my)),
(ox - h, oy + round(i * my)),
fill='green')
canvas.create_text(ox + ht, oy - round(i * my), text=str(i * -my))
canvas.create_text(ox + ht, oy + round(i * my), text=str(i * my))
canvas.pack()
master.mainloop()
Наброски для отображения функции в виде графика:
import tkinter
# ~~~~~~~~~~~~~~~~~~~~~~~~~
t1 = 1
t2 = 10
h = 1.5
li = []
for t in range(t1, t2 + 1, h):
zf = F(t, n, k)
li.append((t, zf))
li2 = []
for x, y in li:
li2.append((int(x * 10), int(y * 2.5)))
#~~~~~~~~~~~~~~~~~~~~~~~~~
canvas.create_line(li2, fill="blue")
