【问题标题】:Is it possible to get mouse input on tkinter window screen?是否可以在 tkinter 窗口屏幕上获得鼠标输入?
【发布时间】:2019-03-04 15:05:28
【问题描述】:

我正在制作一个个人项目,其中我在 tkinter 的 Toplevel() 窗口中打开一个图像(gif)。使用嵌套循环,我打开多个图像,如下所示:

for img in range(10):       *#####EX: 10 gif files*
    imgfile = "path %i.gif" %img *## Each file is named in series e:g 0, 1, 2,...,9*
    for i in range(30):     *#####considering each gif has 30 frames/slides*
        gif = PhotoImage(file=imgfile, format="gif -index %d" %i)
        canvas.create_image(o,o, image=gif, anchor=NW)
        canvas.update()
>>>

在 canvas.update() 之后,我想等待用户在外循环的下一次迭代开始之前在任意位置单击 tkinter 窗口屏幕。 在 ln 7 中,我必须在“>>>”旁边使用什么命令。

【问题讨论】:

    标签: python tkinter


    【解决方案1】:
    from tkinter import *
    
    i = 0
    main = Tk()
    flag = IntVar(value=1)
    
    def click():
        flag.set(1)
    
    bt = Button(main, command=click, text='continue')
    bt.grid()
    
    print('looping')
    while i < 50 and flag.get():
        i += 1
        flag.set(0)
        print(i)
        bt.wait_variable(flag)
    
    main.mainloop()
    

    我认为这个小演示代码可以帮助您解决问题。 每次点击按钮,屏幕上都会打印出增加的 i,就像您的多张图片一样。

    【讨论】:

      【解决方案2】:

      您可以将鼠标单击事件绑定到窗口并在鼠标单击事件处理程序中更新图像。下面是一个例子:

      import tkinter as tk
      
      file_idx = 0
      image_idx = 0
      
      def update_image():
          global file_idx, image_idx
          imgfile = 'path %i.gif' % file_idx
          canvas.gif = tk.PhotoImage(file=imgfile, format='gif -index %d'%image_idx)
          canvas.create_image(0, 0, image=canvas.gif, anchor='nw')
          image_idx = (image_idx + 1) % 30
          if image_idx == 0: file_idx = (file_idx + 1) % 10
      
      root = tk.Tk()
      
      canvas = tk.Canvas(width=800, height=600)
      canvas.pack()
      
      root.bind('<Button-1>', lambda e: update_image())
      root.mainloop()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-21
        • 1970-01-01
        • 2020-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多