我今天下午已经问了一个关于如何在Tkinter更新标签的问题,得到了一个有效的答案。
但是,我发现“解决方案”代码有点长,并试图改进它。
基本上我使用updt
函数在标签method
上执行配置lbl
。该方法将通过调用gravitation
函数来更改标签文本。
每次我点击某个地方时,我都会在整个窗口上使用bind方法来调用updt
函数。
现在的问题是程序无法正常工作,因为标签中显示的数字不正确,并且尽管行星与之前的距离相同,但并不总是显示相同的值。
我仔细阅读了每一行,但由于我对编程很陌生,所以我找不到错误。
我正在使用Python 3。
以下是我之前的代码:Update Tkinter Label
这是新的:
from tkinter import *
import math
x, y = 135, 135
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)
if dist != 0:
grav = 6.67384/dist
else:
grav = "Infinite"
str(grav)
return grav
def updt (event):
lbl.configure (text = gravitation(oval1, oval2))
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.grid(row=0, column=1, sticky =W, padx = 5, pady = 5, rowspan =4)
Button(wind, text = 'Quit', command=wind.destroy).grid(row=5, column=1, sticky =W, padx = 5, pady = 5)
wind.bind ("<Button-1>", updt)
oval1 = can.create_oval(x,y,x+30,y+30,width=2,fill='orange') #Planet 1 moving etc
Button(wind, text = 'Left', command=moveLeft).grid(row=0, column=2, sticky =W, padx = 5, pady = 5)
Button(wind, text = 'Right', command=moveRight).grid(row=1, column=2, sticky =W, padx = 5, pady = 5)
Button(wind, text = 'Top', command=moveTop).grid(row=2, column=2, sticky =W, padx = 5, pady = 5)
Button(wind, text = 'Bottom', command=moveBottom).grid(row=3, column=2, sticky =W, padx = 5, pady = 5)
oval2 = can.create_oval(x+50,y+50,x+80,y+80,width=2,fill='blue') #Planet 2 moving etc
Button(wind, text = 'Left', command=moveLeft2).grid(row=0, column=3, sticky =W, padx = 5, pady = 5)
Button(wind, text = 'Right', command=moveRight2).grid(row=1, column=3, sticky =W, padx = 5, pady = 5)
Button(wind, text = 'Top', command=moveTop2).grid(row=2, column=3, sticky =W, padx = 5, pady = 5)
Button(wind, text = 'Bottom', command=moveBottom2).grid(row=3, column=3, sticky =W, padx = 5, pady = 5)
lbl = Label(wind, bg = 'white')#label
lbl.grid(row=4, column=1, sticky =W, padx = 5, pady = 5, columnspan = 3)
gravitation (oval1, oval2)
wind.mainloop()
答案 0 :(得分:0)
updt
会触发,当用户点击按钮时会触发移动功能,然后释放它。因此,在移动函数之前始终会调用updt
。因此,标签会在移动到新位置之前报告行星彼此之间的重力。
不是将updt
绑定到全局点击事件,而是在坐标更改后将其放在move
函数中。
def updt():
lbl.configure (text = gravitation(oval1, oval2))
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)
updt()