如何让tkinter横向线条在指定纵向线条区间内移动以实现道路效果
Tkinter 2D道路显示效果修改方案
核心修改逻辑
- 提取最外侧两条纵向标线的端点坐标,计算两条线的线性方程,可根据任意y坐标得到对应位置的道路左右边界x值
- 横向线条刷新时动态调整两端x坐标,使其始终限制在左右纵向标线的区间内,不会超出道路范围
- 保留原有移动循环和纵向线条生成逻辑,无需额外拆分列表
import time from tkinter import * class Template: def __init__(self): self.window = Tk() self.window.title("2D Display") self.canvas = self.canvas_display() self.line1 = self.line_creation(650,350,500 * .3, 1000) # 计算最左侧纵向线的线性参数 left_line_coords = self.canvas.coords(self.line1[0]) lx1, ly1, lx2, ly2 = left_line_coords self.left_k = (ly2 - ly1) / (lx2 - lx1) self.left_b = ly1 - self.left_k * lx1 # 计算最右侧纵向线的线性参数 right_line_coords = self.canvas.coords(self.line1[-1]) rx1, ry1, rx2, ry2 = right_line_coords self.right_k = (ry2 - ry1) / (rx2 - rx1) self.right_b = ry1 - self.right_k * rx1 self.line3 = self.line_movement_creation(0, 350,2000, 350) self.horizon = self.canvas.create_line(0,350,2000, 350, width = 2, fill ="white") self.speedx = 0 self.speedy = 9 self.active = True self.pos1 = [] self.move_active() self.canvas.update() def canvas_display(self): canvas = Canvas(self.window, width=500, height=400, background='black') canvas.pack(expand=True, fill="both") canvas.update() return canvas def line_creation(self,x,y,x1,y1): spacing = 0 lines = [] for i in range(11): id = self.canvas.create_line( x, y, x1 + spacing, y1, width=2, fill="white") lines.append(id) spacing += 100 pos1 = self.canvas.coords(id) self.pos1 = pos1 return lines def line_movement_creation(self,x,y,x1,y1): spacing1 = 0 lines = [] for i in range(4): current_y = y + spacing1 # 按当前高度的道路边界生成横向线 left_x = (current_y - self.left_b) / self.left_k right_x = (current_y - self.right_b) / self.right_k id = self.canvas.create_line(left_x , current_y, right_x, current_y, width=2, fill="white") lines.append(id) spacing1 += 100 return lines def line_update(self): for line in self.line3: pos = self.canvas.coords(line) new_y = pos[1] + self.speedy # 超出下边界后重置到地平线位置循环 if new_y >= 800: new_y = 350 # 动态调整横向线长度匹配当前道路宽度 left_x = (new_y - self.left_b) / self.left_k right_x = (new_y - self.right_b) / self.right_k self.canvas.coords(line, left_x, new_y, right_x, new_y) def move_active(self): if self.active: self.line_update() self.window.after(40, self.move_active) def run(self): self.window.mainloop() if __name__ == '__main__': Temp = Template() Temp.run()
内容的提问来源于stack exchange,提问作者user14232195
相关产品推荐
相关产品推荐

