在Tkinter/python中显示

2024-09-29 06:25:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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()

我试过了。但是我找不到任何能不断显示数字并随着圆圈的移动而改变的东西。你知道吗


Tags: textmovedefcolumnbuttoncommandgridrow
1条回答
网友
1楼 · 发布于 2024-09-29 06:25:19

使用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.

相关问题 更多 >