【问题标题】:Can I paint on the tkinter canvas twice simultaneously?我可以同时在 tkinter 画布上作画两次吗?
【发布时间】:2022-11-25 11:10:50
【问题描述】:

当光标在画布上时,我希望光标的 x 和 y 坐标由两条滑动线跟踪。一个位于画布顶部,受限于 x,另一个位于画布左侧,受限于 y。

我实际上已经实现了这一点,几乎:

import tkinter as tk

def callback(event):
    draw_y_marker(event.y)
    draw_x_marker(event.x)

def draw_x_marker(x):
    paint.coords(line, x, 0, x, 20)

def draw_y_marker(y):
    paint.coords(line, 0, y, 20, y)

root = Tk()
paint = Canvas(root)
paint.bind('<Motion>', callback)
paint.pack()

line = paint.create_line(x, 0, x, height)
root.mainloop()

如果我在回调中注释掉 draw_y_marker 调用,我会得到一条限制为 x 的线,它沿着屏幕顶部滑动,标记光标位置。如果我注释掉 draw_x_marker,我会得到限制为 y 沿屏幕一侧滑动的线。

但不是两者都是我想要的!如果我取消注释两者,则只有 draw_x_marker 方法有效。如何同时在画布上绘制两个东西?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    您在画布中只创建了一个订单项,那么如何显示两条滑动线?

    您需要为 x 和 y 创建两条滑动线并在 callback() 中更新它们:

    import tkinter as tk
    
    def callback(event):
        draw_y_marker(event.y)
        draw_x_marker(event.x)
    
    def draw_x_marker(x):
        paint.coords(xline, x, 0, x, 20)
    
    def draw_y_marker(y):
        paint.coords(yline, 0, y, 20, y)
    
    root = tk.Tk()
    paint = tk.Canvas(root)
    paint.bind('<Motion>', callback)
    paint.pack()
    
    # create the two sliding lines initially
    xline = paint.create_line(0, 0, 0, 0)
    yline = paint.create_line(0, 0, 0, 0)
    
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多