【问题标题】:Displaying in Tkinter/python在 Tkinter/python 中显示
【发布时间】:2016-06-04 03:53:54
【问题描述】:

我试图在 Tkinter 窗口中显示我的两个圆圈之间的距离。我找到了一个算法,但我在显示它时遇到了问题。到目前为止,这是我的程序:

from Tkinter import *
from math import *

def planetM(gd, hb):
    global x1, y1
    x1, y1 = x1+gd, y1+hb
    can1.coords(oval1,x1, y1, x1+30, y1+30)

def planetU(gd, hd):
    global z1, v1
    z1, v1 = z1+gd, v1+hd
    can1.coords(oval2, z1, v1, z1+30, v1+30)

def move_M_up():
    planetM(0, -10)
def move_U_up():
    planetU(0, -10)
def move_M_down():
    planetM(0, 10)
def move_U_down():
    planetU(0, 10)
def move_M_right():
    planetM(10, 0)
def move_U_right():
    planetU(10, 0)
def move_M_left():
    planetM(-10, 0)
def move_U_left():
    planetU(-10, 0)

def distance():
    dist = math.sqrt((x1-z1)**2 + (y1-v1)**2) -  30
    chain.configure(text='dist :' + str(dist))

x1, y1, z1, v1 = 10, 10, 260, 260

win1 = Tk()
win1.title("Two planets")

can1 = Canvas(win1, bg='black', height = 300, width=300)
oval1= can1.create_oval(x1,y1,x1+30,y1+30, width=2, fill='orange')
oval2= can1.create_oval(z1,v1,z1+30,v1+30, width=2, fill='blue')
can1.grid(row=1, column =1, rowspan = 9)
Button(win1, text='Exit', command= win1.quit).grid(row=1, column =2)
Button(win1, text='M left', command=move_M_left).grid(row=2, column=2)
Button(win1, text='M right', command=move_M_right).grid(row=3, column=2)
Button(win1, text='M down', command=move_M_down).grid(row=4, column=2)
Button(win1, text='M up', command=move_M_up).grid(row=5, column=2)
Button(win1, text='U left', command=move_U_left).grid(row=6, column=2)
Button(win1, text='U right', command=move_U_right).grid(row=7, column=2)
Button(win1, text='U down', command=move_U_down).grid(row=8, column=2)
Button(win1, text='U up', command=move_U_up).grid(row=9, column=2)
chain = Label(win1)
chain.grid(row = 10, column=1)

win1.mainloop()

我尝试了 .bind,但找不到任何可以不断显示数字并随着圆圈移动而改变数字的东西。

【问题讨论】:

  • 不要使用通配符导入。

标签: python tkinter label


【解决方案1】:

使用after 方法。使其每 0.1 秒刷新一次标签。

win1.after(100, distance)    # Number 100 represents time in milliseconds to wait before function distance is called
                             # This needs to be placed BEFORE mainloop.

然后用同样的方法让函数距离调用自己:

def distance():
    dist = math.sqrt((x1-z1)**2 + (y1-v1)**2) -  30
    chain.configure(text='dist :' + str(dist))
    win1.after(100, distance)

注意:如果你是从数学中导入的:from math import *,那么你不能说:math.sqrt()。因此,要么将导入更改为:import math,要么删除 math.

【讨论】:

    猜你喜欢
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2014-05-24
    • 2016-04-04
    相关资源
    最近更新 更多