[英]Tkinter event for DownPress of mouse button (holding down)?
更新:這似乎是一個版本問題。 該事件不會在單擊 python 3.6.1 時觸發,但適用於我迄今為止測試過的 2.7。
更新: Bryan 的回答確實解決了我的問題,即該事件無法正常工作,但是在我的 3.6.1 版本的 python 上,事件未在向下單擊時觸發的問題仍然是一個問題。
Python 版本 = 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)]
我正在嘗試編寫一個事件處理程序以在按住鼠標按鈕時重復執行某些操作。 我一直在搜索文檔和互聯網,但找不到任何關於按住鼠標左鍵的參考。
是否有專門用於按住鼠標左鍵的事件? 有一個用於發布<ButtonRelease-1>
的偶數,但沒有一個用於單擊並按住事件的接縫。
我已經嘗試過<Button-1>
及其所有同義事件以防萬一,但沒有運氣。 該事件僅在發布時觸發,但不會在我想要的向下單擊時觸發。 我什至不需要一個持續按住按鈕的事件,我只需要一個均勻的按下按鈕。
歡迎提供文檔,因為我找不到任何東西。
更新:
這是一個示例代碼。 它只會在釋放按鈕時打印。 請記住,我正在嘗試按下滾動條上的箭頭按鈕並更改滾動速度。
滾動條處理按下滾動箭頭的方式是否與按鈕不同?
import tkinter as tk
root = tk.Tk()
textbox = tk.Text(root, height = 10)
textbox.grid(row=0, column=0)
scrolling = False
yscroll = tk.Scrollbar(root, command=textbox.yview,orient="vertical", repeatinterval=10, repeatdelay=30)
textbox.configure(yscrollcommand = yscroll.set)
yscroll.grid(row=0, column=1, sticky="ns")
for i in range(1000):
textbox.insert(tk.END, "{}\n".format(i))
def scrolling_active(arrow):
global scrolling
root.bind('<ButtonRelease-1>', stop_scrolling())
print(arrow)
if scrolling == True:
if arrow == "arrow1":
textbox.tk.call(textbox._w,'yview', 'scroll', -100, 'units')
if arrow == "arrow2":
textbox.tk.call(textbox._w,'yview', 'scroll', 100, 'units')
root.after(100, lambda a = arrow: scrolling_active(a))
def start_scrolling(event):
global scrolling
scrolling = True
scrolling_active(yscroll.identify(event.x, event.y))
def stop_scrolling():
global scrolling
scrolling = False
yscroll.bind("<Button-1>", start_scrolling)
root.mainloop()
沒有按住按鈕的事件。 只有按下和釋放按鈕的事件。
如果您需要在按鈕按下時進行跟蹤,您可以在按下時設置標志並在釋放時取消設置。
在您的代碼中,您有一個錯誤。 考慮這段代碼:
root.bind('<ButtonRelease-1>', stop_scrolling())
它在功能上與此相同:
result=stop_scrolling()
root.bind('<ButtonRelease-1>`, None)
要進行綁定,您必須刪除()
:
root.bind('<ButtonRelease-1>', stop_scrolling)
您還需要stop_scrolling
來接受事件對象:
def stop_scrolling(event):
global scrolling
scrolling = False
也沒有必要調用textbox.tk.call
。 您可以在 tkinter 對象上調用yview
方法( textbox.yview textbox.yview("scroll", -100, "units"
)
我知道這有點晚了,但我想做完全相同的事情(在畫布中拖動圖像以制作操縱桿控制器)。
閱讀文檔事件和綁定我發現了這個事件: '<B1-Motion>'
這是我做的工作示例:
from tkinter import *
root = Tk()
root.geometry('800x600')
image1 = PhotoImage(file = 'images/button.png')
x_img,y_img = 250,250
canvas = Canvas(root, width = 500, height = 400, bg = 'white')
canvas.pack()
imageFinal = canvas.create_image(x_img, y_img, image = image1)
def move(event):
global x_img,y_img
x, y = event.x, event.y
print('{}, {}'.format(x, y))
canvas.move(imageFinal, x-x_img,y-y_img)
x_img = x
y_img = y
canvas.update()
canvas.bind('<B1-Motion>', move)
root.mainloop()
您應該能夠在最初單擊鼠標時綁定到<ButtonPress-1>
,然后調用重復函數,直到<ButtonRelease-1>
停止它,正如您所提到的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.