Умоляю!!Необходимо перемещать букву внутри поля Text.

ttd2001

Новичок
Пользователь
Мар 17, 2022
12
1
3
Никак не могу додуматься, может вы поможете люди добрые!)


Python:
# Контрольная работа студентки группы 20-ЗИЭ Трофимовой Т.Д.
# Дисциплина - Высокоуровневые технологии программирования
# Вариант № 2-26.
# Контрольная работа №2. Задача №3.
"""
На форме располагаются:
компонент Canvas размером 200х200, в левом верхнем углу которого находится рисунок размером 40х40;
редактор Text размером 5х5, в левом верхнем углу которого находится латинский символ а;
четыре кнопки со стрелками ↑, ↓, →, ←; две линейки Scale на пять положений.
Кнопки со стрелками синхронно перемещают символ в редакторе и рисунок в контейнере Canvas строго
по периметру, а линейки Scale показывают текущее положение фигур по горизонтали и вертикали.
Закрывает приложение двойной клик по форме.
"""
"""
Кнопки со стрелками синхронно перемещают символ в редакторе и рисунок в контейнере Canvas строго
по периметру, а линейки Scale показывают текущее положение фигур по горизонтали и вертикали.
Закрывает приложение двойной клик по форме.
"""

import sys
from tkinter import *
from turtle import width
from PIL import Image, ImageTk
 
#Начальные координаты по X и Y
dx = 10
dy = 10
ix = 30
iy = 30
#Компонент Canvas
def elementCanvas():
    global elCanvas
    elCanvas = Canvas(
    root,
    width=200,
    height=200,
    bg='white')
    elCanvas.place(x = dx, y = dy+10)
    elCanvas.pack()
    #Изображение
def elementImage():
    global image
    global item
    image = ImageTk.PhotoImage(Image.open("cat(4040).jpg"))
    item = elCanvas.create_image(ix, iy, image = image)
 
 
def left():
    elCanvas.move(item,-145,0)
  
def right():
    elCanvas.move(item,145,0)
    elText.mark_set("insert", 4.0, (1,0))
def up():
    elCanvas.move(item,0,-145)
def down():
    elCanvas.move(item,0,145)
 
#Редактор Text
def elementText():
    global elText, TextX, TextY
    TextX = dx * 6
    TextY = dy * 2
    elText = Text(width=5, height=5, bg="White", fg='black')
    elText.place(x=29*dx,y=dy)
    elText.insert(1.0, "a")

#Кнопки со стрелками

def leftButton():
    global leftButton, DeltaTextX, DeltaTextY
    DeltaTextX = TextX
    DeltaTextY = TextY
    leftButton=Button(text="←", bg="white", fg="black", justify="center", width=1, height=1,command=left)
    leftButton.place(x=10, y=237)
    
 
def upButton():
    global upButton
    upButton=Button(text="↑", bg="white", fg="black", justify="center", width=1, height=1,command=up)
    upButton.place(x=35, y=220)
 
 
def rightButton():
    global rightButton
    rightButton=Button(text="→", bg="white", fg="black", justify="center", width=1, height=1,command=right)
    rightButton.place(x=60, y=237)
  
 
def downButton():
    global downButton
    downButton=Button(text="↓", bg="white", fg="black", justify="center", width=1, height=1,command=down)
    downButton.place(x=35, y=255)
 
 
#Линейки Scale
#Горизонатльная линейка Scale
def elementScalehorizontal():
    global elScalehorizontal
    #Горизонатльная линейка Scale
    elScalehorizontal = Scale(orient='horizontal',resolution=1, from_=0, to=4)
    elScalehorizontal.place(x=dx*10, y=22*dy)
    def oneposition ():
        global onehor
        elementScalehorizontal.get(item, -145, 0)
#Вертикальная линейка Scale
def elementScalevertical():
    global elScalevertical
    elScalevertical = Scale(orient='vertical',resolution=1, from_=0, to=4)
    elScalevertical.place(x=29*dx, y=10*dy)
 
#Окно программы
def mainWindowProgram():
    elementCanvas()
    elementText()
    leftButton()
    upButton()
    rightButton()
    downButton()
    elementScalehorizontal()
    elementScalevertical()
 
#Вызов программы
def application():
    global root
    global event
    root = Tk()
    root.title("20-ЗИЭ Контрольная работа №2. Задание №3. Вариант 2-26. Трофимова Т.Д.")
    root.geometry("350x350")
    root.resizable(0,0)
    mainWindowProgram()
    elementImage()
    elCanvas.bind('<Down>', down)
    elCanvas.bind('<Right>', right)
    elCanvas.bind('<Up>', up)
    elCanvas.bind('<Left>',left)
    """root.bind("<Double-Button-1>", lambda CloseWindowProgram: root.destroy())"""
    root.mainloop()
 
application()
 

Vershitel_sudeb

Vershitel sudeb
Команда форума
Модератор
Мар 17, 2021
973
220
43
21
Москва
например ты знаешь что буква имеет координаты x=2, y=0
Python:
x=2
y=0
text = [[" ", " ", " ", " ", " "],
        [" ", " ", " ", " ", " "],
        [" ", " ", " ", " ", " "],
        [" ", " ", " ", " ", " "],
        [" ", " ", " ", " ", " "]]
text[y][x] = 'a'
text = '\n'.join(map(''.join, text))
ну и вставь куда надо
 

Vershitel_sudeb

Vershitel sudeb
Команда форума
Модератор
Мар 17, 2021
973
220
43
21
Москва
Полный код
Python:
from PIL import Image, ImageTk
import tkinter as tk
app = tk.Tk()
# Положение картинки и буквы (x, y)
pos = [0, 0]
# Параметры кнопки
btn_params = {'bg': "white",
              'fg': "black",
              'justify': "center",
              'width': 1,
              'height': 1}
add = [[0, -1], [-1, 0], [1, 0], [0, 1]]

def move_text():
    """
    Двигает текст
    """
    txt = [[" ", " ", " ", " ", " "],
           [" ", " ", " ", " ", " "],
           [" ", " ", " ", " ", " "],
           [" ", " ", " ", " ", " "],
           [" ", " ", " ", " ", " "]]
    txt[pos[1]][pos[0]] = 'a'
    txt = '\n'.join(map(''.join, txt))
    text.delete('1.0', tk.END)
    text.insert('0.0', txt)

def ml(n):
    return lambda: move(n)

def move(n):
    # Генерим новое положение
    new_pos = [pos[0] + add[n][0], pos[1] + add[n][1]]
    # Если оно на периметре
    if ((0 in new_pos) or (4 in new_pos)) and 0 <= new_pos[0] < 5 and 0 <= new_pos[1] < 5:
        # Сохраняем его как основное
        pos[0], pos[1] = new_pos[0], new_pos[1]
        # Двигаем текст
        move_text()
        # Двигаем картинку
        canvas.moveto(img, pos[0]*40, pos[1]*40)
        # Двигаем линейки
        sx.set(pos[0])
        sy.set(pos[1])

# Создаем canvas
canvas = tk.Canvas(width=200,
                   height=200,
                   bg='white')
canvas.grid(row=0, column=0)
# Создаем картинку
image = ImageTk.PhotoImage(Image.open("./src/img/serd.png"))
img = canvas.create_image(20, 20, image=image)
# Создаем кнопки
btns = tk.Frame()
btns.grid(row=1, column=0)
tk.Button(btns, text='↑', **btn_params, command=ml(0)).grid(column=1, row=1)
tk.Button(btns, text='←', **btn_params, command=ml(1)).grid(column=0,
                                                            row=2)
tk.Button(btns, text='→', **btn_params, command=ml(2)).grid(column=2,
                                                            row=2)
tk.Button(btns, text='↓', **btn_params, command=ml(3)).grid(column=1,
                                                            row=3)
# Создаем текстовое поле
text = tk.Text(width=5, height=5)
text.grid(row=0, column=1, sticky='n')
text.insert('0.0', 'a')
# Создаем линейки
sx = tk.IntVar(value=0)
sy = tk.IntVar(value=0)
lins = tk.Frame()
lins.grid(row=1, column=1)
linx = tk.Scale(lins,
                orient='horizontal',
                resolution=1,
                from_=0,
                to=4,
                variable=sx,
                state='disabled')
linx.grid(row=0, column=1)
liny = tk.Scale(lins,
                orient='vertical',
                resolution=1,
                from_=0,
                to=4,
                variable=sy,
                state='disabled')
liny.grid(row=1, column=0)
# Запускаем программу
app.mainloop()
 
  • Мне нравится
Реакции: ttd2001

ttd2001

Новичок
Пользователь
Мар 17, 2022
12
1
3
Полный код
Python:
from PIL import Image, ImageTk
import tkinter as tk
app = tk.Tk()
# Положение картинки и буквы (x, y)
pos = [0, 0]
# Параметры кнопки
btn_params = {'bg': "white",
              'fg': "black",
              'justify': "center",
              'width': 1,
              'height': 1}
add = [[0, -1], [-1, 0], [1, 0], [0, 1]]

def move_text():
    """
    Двигает текст
    """
    txt = [[" ", " ", " ", " ", " "],
           [" ", " ", " ", " ", " "],
           [" ", " ", " ", " ", " "],
           [" ", " ", " ", " ", " "],
           [" ", " ", " ", " ", " "]]
    txt[pos[1]][pos[0]] = 'a'
    txt = '\n'.join(map(''.join, txt))
    text.delete('1.0', tk.END)
    text.insert('0.0', txt)

def ml(n):
    return lambda: move(n)

def move(n):
    # Генерим новое положение
    new_pos = [pos[0] + add[n][0], pos[1] + add[n][1]]
    # Если оно на периметре
    if ((0 in new_pos) or (4 in new_pos)) and 0 <= new_pos[0] < 5 and 0 <= new_pos[1] < 5:
        # Сохраняем его как основное
        pos[0], pos[1] = new_pos[0], new_pos[1]
        # Двигаем текст
        move_text()
        # Двигаем картинку
        canvas.moveto(img, pos[0]*40, pos[1]*40)
        # Двигаем линейки
        sx.set(pos[0])
        sy.set(pos[1])

# Создаем canvas
canvas = tk.Canvas(width=200,
                   height=200,
                   bg='white')
canvas.grid(row=0, column=0)
# Создаем картинку
image = ImageTk.PhotoImage(Image.open("./src/img/serd.png"))
img = canvas.create_image(20, 20, image=image)
# Создаем кнопки
btns = tk.Frame()
btns.grid(row=1, column=0)
tk.Button(btns, text='↑', **btn_params, command=ml(0)).grid(column=1, row=1)
tk.Button(btns, text='←', **btn_params, command=ml(1)).grid(column=0,
                                                            row=2)
tk.Button(btns, text='→', **btn_params, command=ml(2)).grid(column=2,
                                                            row=2)
tk.Button(btns, text='↓', **btn_params, command=ml(3)).grid(column=1,
                                                            row=3)
# Создаем текстовое поле
text = tk.Text(width=5, height=5)
text.grid(row=0, column=1, sticky='n')
text.insert('0.0', 'a')
# Создаем линейки
sx = tk.IntVar(value=0)
sy = tk.IntVar(value=0)
lins = tk.Frame()
lins.grid(row=1, column=1)
linx = tk.Scale(lins,
                orient='horizontal',
                resolution=1,
                from_=0,
                to=4,
                variable=sx,
                state='disabled')
linx.grid(row=0, column=1)
liny = tk.Scale(lins,
                orient='vertical',
                resolution=1,
                from_=0,
                to=4,
                variable=sy,
                state='disabled')
liny.grid(row=1, column=0)
# Запускаем программу
app.mainloop()
Абалдеть, вы просто гений!!! Мои аплодисменты вам) Я вчера пробовала через метод инсерт, но это было максимально тупо, поэтому я вас бесконечно благодарю *)
 
  • Мне нравится
Реакции: Vershitel_sudeb

Форум IT Специалистов