0
我正在創建一個Tkinter程序,該程序根據保存到文本文件的角度創建一個顯示車輛位置的畫布。我遇到的問題是,程序僅在啓動時讀取文本文件,並且不會繼續檢查。我知道這應該是相當簡單的,但我已經看過很多網站,無法找到一種方法來做到這一點。這裏是我的代碼試圖根據文本文件更新Tkinter中的行位置
from Tkinter import *
import math
import time
root = Tk()
root.geometry("800x480")
root.configure(background='darkgrey')
content = Frame(root,)
#Dimensions of Window
w = 800
h = 480
#Get Angle
file_angle = open("current_angle.txt")
#read file and remove "/n" from the end of the string
string_angle = ((file_angle.read())[:-2])
#Convert string to a number
read_angle = float(string_angle)
if read_angle > 90 or read_angle <-90:
deg_angle = read_angle - 180
else:
deg_angle = read_angle
angle = math.radians(deg_angle)
swath_width = w/5
if deg_angle > -90 and deg_angle < 90:
#Center Line
centertopx = (w/2) + ((h/1.5) * math.tan(angle))
centertopy = 0
centerbottomx = (w/2) + ((h - (h/1.5)) * math.tan(-1 * angle))
centerbottomy = h
if deg_angle == 90 or deg_angle == -90:
centertopx = 0
centertopy = h/2
centerbottomx = w
centerbottomy = h/2
#Create Guidance Map
livemap = Canvas(root, width=w, height=h)
#Outline of map
livemap.create_rectangle(0,0,w,h, outline="black", width=5, fill="#9E9E9E")
#Drawing lines
livemap.create_line(centertopx, centertopy, centerbottomx, centerbottomy, fill="red", width=4)
#stationary parts of map
#Triangle that represents vehicle
livemap.create_polygon(
((w/2)-(w * 0.04)),((h/1.5)+(h * 0.1)),((w/2)+(w * 0.04)),((h/1.5)+(h * 0.1)),(w/2),(h/1.5),
outline="black", fill="darkorange", width=2)
livemap.create_line((w/2),((h/1.5)+(h*0.07)),(w/2),(h/1.5),fill="black", width=2)
livemap.create_polygon(((w/2)-(w * 0.04)),((h/1.5)+(h * 0.1)),((w/2)+(w * 0.04)),((h/1.5)+(h * 0.1)),(w/2),((h/1.5)+(h*0.07)),
outline="black", fill="darkorange", width=2)
#Put canvas into window
livemap.grid(column=0, row=0, columnspan=4, rowspan=4)
root.mainloop()
您可以使用'root.after(miliseconds,function_name)'來定期運行將再次讀取文件的函數。順便說一句:再次從文件中讀取,您必須關閉並再次打開它,否則您必須使用'file_angle.seek(0)'移動到文件開頭。 – furas