Monday, 2 September 2013

Update Tkinter Label

Update Tkinter Label

I use Python 3 and I'm quite new to programming. I have written a code
that's supposed to show a window in which you can move around two planets
and see the gravitational force between them. Everything works excepted
the label that's supposed to display the force. After multiple attempts
and searches, I just can't find out how to update it every time a planet
is being moved.
I guess my problem should be in the last line with :
lbl = Label(wind, bg = 'white', text = gravitation(oval1,
oval2)).pack(padx=5, pady=5)
I've tried to use a StringVar and a textvariable parameter but I didn't
really get the concepts of it.
Here is my code. I guess the answer is easy but I'm quite unexperienced.
from tkinter import *
import math
x, y = 135, 135
gravitation = 0
def gravitation (obj1,obj2):
a, b, c, d = can.coords (obj1)
e, f, g, h = can.coords (obj2)
dist = math.sqrt ((((a+c)/2)-((e+g)/2))**2+(((b+d)/2)-((f+h)/2))**2)
grav = 6.67384/dist
return grav
def move (ov, lr, tb): # function to move the ball
coo = can.coords(ov)
coo[0] = coo[0] + lr
coo[1] = coo[1] + tb
coo[2] = coo[0]+30
coo[3] = coo[1]+30
can.coords(ov, *coo)
def moveLeft ():
move(oval1, -10, 0)
def moveRight ():
move(oval1, 10, 0)
def moveTop ():
move(oval1, 0, -10)
def moveBottom ():
move(oval1, 0, 10)
def moveLeft2 ():
move(oval2, -10, 0)
def moveRight2 ():
move(oval2, 10, 0)
def moveTop2 ():
move(oval2, 0, -10)
def moveBottom2 ():
move(oval2, 0, 10)
##########MAIN############
wind = Tk() # Window and canvas
wind.title ("Move Da Ball")
can = Canvas (wind, width = 300, height = 300, bg = "light blue")
can.pack (side = LEFT,padx = 5, pady = 5)
Button(wind, text = 'Quit', command=wind.destroy).pack(padx = 5, pady = 5)
oval1 = can.create_oval(x,y,x+30,y+30,width=2,fill='orange') #Planet 1
moving etc
Button(wind, text = 'Left', command=moveLeft).pack(padx = 5, pady = 5)
Button(wind, text = 'Right', command=moveRight).pack(padx = 5, pady = 5)
Button(wind, text = 'Top', command=moveTop).pack(padx = 5, pady = 5)
Button(wind, text = 'Bottom', command=moveBottom).pack(padx = 5, pady = 5)
oval2 = can.create_oval(x+50,y+50,x+80,y+80,width=2,fill='orange') #Planet
2 moving etc
Button(wind, text = 'Left', command=moveLeft2).pack(padx = 5, pady = 5)
Button(wind, text = 'Right', command=moveRight2).pack(padx = 5, pady = 5)
Button(wind, text = 'Top', command=moveTop2).pack(padx = 5, pady = 5)
Button(wind, text = 'Bottom', command=moveBottom2).pack(padx = 5, pady = 5)
lbl = Label(wind, bg = 'white', text = gravitation(oval1,
oval2)).pack(padx=5, pady=5)
wind.mainloop()

No comments:

Post a Comment