Найти - Пользователи
Полная версия: проблема в Tkinter перемещение фигуры
Начало » GUI » проблема в Tkinter перемещение фигуры
1
datgenn
проблема вот в чем,я изменяю длину и ширину скроллами, когда я двигаю скролл вызывается функция и в функции находится метод coords который изменяет координаты.Одним скроллом я изменяю предпоследнюю координату,то есть изменяю ширину фигуры,а вторым я изменяю последнюю,то есть высоту.проблемы вот в чем когда этот метод вызывается я должен обязательно ему дать еще и координаты x и y.

def sca(event):
    p=j+sca2.get()
    pole.coords(curentfigure,x,y,z+sca1.get(),p)
def scaa(event):
    r=z+sca1.get()
    pole.coords(curentfigure,x,y,r,j+sca2.get())

беда вот в чем у меня еще вызывается move для передвижения фигуры
def right(event):
    pole.move(curentfigure,5,0)
и тут изменяются координаты x и y.
То есть когда я передвину фигуру куда нибудь и решу изменить ширину или высоту вызовится coords соответсятвенно ему нужно взять x и y.А x и y я могу взять только дефолтные и получается так что я когда изменю ширину или высоту у меня фигура возвратится на свою начальную позицию.Подскажите как сделать так чтобы фигура не возвращалась обратно.
Спасибо.

Вот весь код:
from tkinter import *
root=Tk()
root.title('Первая лаба')
root.minsize(width = 500, height=430)
root.maxsize(width = 500, height=430)
def red():
    pole.itemconfig('group1',fill="red")
def green():
    pole.itemconfig('group1',fill="green")
def blue():
    pole.itemconfig('group1',fill="blue")
def red1():
    pole.itemconfig('group1',outline="red")
def green1():
    pole.itemconfig('group1',outline="green")
def blue1():
    pole.itemconfig('group1',outline="blue")
def close():
    root.destroy()
def about():
    win = Toplevel(root,bd=10,bg="lightblue")
    win.title("About")
    win.minsize(width=400,height=210)
    win.maxsize(width=400,height=210)
    photo = PhotoImage(file="image.gif",width=150,height=180)
    lab7=Label(win,image=photo)
    lab7.image = photo
    lab7.place(x=0,y=0)
    lab5=Label(win,text="вмвм",bg="lightblue")
    lab5.place(x=200,y=10)
   
m = Menu(root)
root.config(menu=m)
er=Menu(m)
fm=Menu(m)
gt=Menu(m)
m.add_cascade(label="Menu",menu=er)
er.add_command(label="About",command=about)
er.add_command(label="Exit",command=close)
m.add_cascade(label="Цвет фигуры",menu=fm) #пункту располагается на основном меню (m)
fm.add_command(label="Red",command=red) #формируется список команд пункта меню
fm.add_command(label="Green",command=green)
fm.add_command(label="Blue",command=blue)
m.add_cascade(label="Цвет грани",menu=gt)
gt.add_command(label="Red",command=red1)
gt.add_command(label="Green",command=green1)
gt.add_command(label="Blue",command=blue1)
def display():
    global curentfigure
    global x
    global y
    global z
    global j
    v=var.get()
    if v==0:
        pole.delete('all')
        x=10
        y=10
        z=100
        j=100
        sca1.set(0)
        sca2.set(0)
        p=pole.create_rectangle(x,y,z,j,fill="white",outline="blue",tag="group1")
    elif v==1:
        pole.delete('all')
        x=10
        y=10
        z=140
        j=100
        sca1.set(0)
        sca2.set(0)
        p=pole.create_rectangle(x,y,z,j,fill="white",outline="blue",tag="group1")
    elif v==2:
        pole.delete('all')
        x=10
        y=10
        z=100
        j=100
        sca1.set(0)
        sca2.set(0)
        p=pole.create_oval([x,y],[z,j],fill="white",outline="blue",tag="group1")
    curentfigure=p
def verh(event):
    pole.move(curentfigure,0,-5)
def vniz(event):
    pole.move(curentfigure,0,5)
def left(event):
    pole.move(curentfigure,-5,0)
def right(event):
    pole.move(curentfigure,5,0)
def sca(event):
    p=j+sca2.get()
    pole.coords(curentfigure,x,y,z+sca1.get(),p)
def scaa(event):
    r=z+sca1.get()
    pole.coords(curentfigure,x,y,r,j+sca2.get())
    
lab = Label(root, text="Выберите фигуру:", font="18")
lab2 = Label(root, text="Ширина:", font="18")
lab4 = Label(root, text="Высота:", font="18")
sca1 = Scale(root,orient=HORIZONTAL,length=150,
          from_=-50,to=50,tickinterval=30,resolution=1)
sca2 = Scale(root,orient=HORIZONTAL,length=150,
          from_=-50,to=50,tickinterval=30,resolution=1)
var=IntVar()
var.set(1)
rad0 = Radiobutton(root,text="квадрат",
          variable=var,value=0,command=display)
rad1 = Radiobutton(root,text="прямоугольник",
          variable=var,value=1,command=display)
rad2 = Radiobutton(root,text="круг",
          variable=var,value=2,command=display)
pole=Canvas(root,width=300,height=300,bg="lightblue")
but1 = Button(root,
          text="Вверх", #надпись на кнопке
          width=10,height=2, #ширина и высота
          bg="white",fg="blue") #цвет фона и надписи
but2 = Button(root,
          text="Вниз", #надпись на кнопке
          width=10,height=2, #ширина и высота
          bg="white",fg="blue") #цвет фона и надписи
but3 = Button(root,
          text="Влево", #надпись на кнопке
          width=5,height=5, #ширина и высота
          bg="white",fg="blue") #цвет фона и надписи
but4 = Button(root,
          text="Вправо", #надпись на кнопке
          width=5,height=5, #ширина и высота
          bg="white",fg="blue") #цвет фона и надписи
sca1.bind('<Button1-Motion>',sca)
sca2.bind('<Button1-Motion>',scaa)
display()
lab.place(x=320,y=5)
lab2.place(x=320,y=105)
lab4.place(x=320,y=190)
sca1.place(x=320,y=130)
sca2.place(x=320,y=210)
rad0.place(x=320,y=40)
rad1.place(x=320,y=60)
rad2.place(x=320,y=80)
but1.bind('<Button-1>',verh)
but2.bind('<Button-1>',vniz)
but3.bind('<Button-1>',left)
but4.bind('<Button-1>',right)
pole.grid(row=0)
but1.place(x=100,y=330)
but2.place(x=100,y=375)
but3.place(x=50,y=330)
but4.place(x=185,y=330)
root.mainloop() 
4kpt
Нужно исправить две функции:
def sca(event):
    figure = pole.find_all()[0]
    x = pole.bbox(figure)[0] + 1
    y = pole.bbox(figure)[1] + 1
    j = pole.bbox(figure)[3] - 1
    new_x = x + 140 + sca1.get()
    pole.coords(figure,x,y,new_x,j)
def scaa(event):
    figure = pole.find_all()[0]
    x = pole.bbox(figure)[0] + 1
    y = pole.bbox(figure)[1] + 1
    z = pole.bbox(figure)[2] - 1
    new_y = y + 100 + sca2.get()
    pole.coords(figure,x,y,z,new_y)
P.S. Я же писал в Вашем вопросе (Вы уже делали пост), как уйти от global. Нафигачили блин аж 5 штук.
sp3
Это то, о чем я говорил.

И еще. Лучше заменить
sca1.bind('<Button1-Motion>',sca)
sca2.bind('<Button1-Motion>',scaa)
На
sca1["command"] = sca
sca2["command"] = scaa
Иначе происходит запаздывание на еденицу, т.е. Motion выполняется раньше, чем меняется значение в sca1 или sca2. В результате на первом шаге размер не изменяется…
datgenn
спасибо вам добрый человек.так получилось что я один из группы решил познавать python ,соответственно и спросить не у кого .
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB