1. 程式人生 > >python3使用tkinter做介面之滑鼠提示(ToolTip)

python3使用tkinter做介面之滑鼠提示(ToolTip)

from tkinter import *
from time import time, localtime, strftime


class ToolTip( Toplevel ):
    """
    Provides a ToolTip widget for Tkinter.
    To apply a ToolTip to any Tkinter widget, simply pass the widget to the
    ToolTip constructor
    """ 
    def __init__( self, wdgt, msg=None, msgFunc=None, delay=1, follow=True ):
        """
        Initialize the ToolTip
        
        Arguments:
          wdgt: The widget this ToolTip is assigned to
          msg:  A static string message assigned to the ToolTip
          msgFunc: A function that retrieves a string to use as the ToolTip text
          delay:   The delay in seconds before the ToolTip appears(may be float)
          follow:  If True, the ToolTip follows motion, otherwise hides
        """
        self.wdgt = wdgt
        self.parent = self.wdgt.master                                          # The parent of the ToolTip is the parent of the ToolTips widget
        Toplevel.__init__( self, self.parent, bg='black', padx=1, pady=1 )      # Initalise the Toplevel
        self.withdraw()                                                         # Hide initially
        self.overrideredirect( True )                                           # The ToolTip Toplevel should have no frame or title bar
        
        self.msgVar = StringVar()                                               # The msgVar will contain the text displayed by the ToolTip        
        if msg == None:                                                         
            self.msgVar.set( 'No message provided' )
        else:
            self.msgVar.set( msg )
        self.msgFunc = msgFunc
        self.delay = delay
        self.follow = follow
        self.visible = 0
        self.lastMotion = 0
        Message( self, textvariable=self.msgVar, bg='#FFFFDD',
                 aspect=1000 ).grid()                                           # The test of the ToolTip is displayed in a Message widget
        self.wdgt.bind( '<Enter>', self.spawn, '+' )                            # Add bindings to the widget.  This will NOT override bindings that the widget already has
        self.wdgt.bind( '<Leave>', self.hide, '+' )
        self.wdgt.bind( '<Motion>', self.move, '+' )
        
    def spawn( self, event=None ):
        """
        Spawn the ToolTip.  This simply makes the ToolTip eligible for display.
        Usually this is caused by entering the widget
        
        Arguments:
          event: The event that called this funciton
        """
        self.visible = 1
        self.after( int( self.delay * 1000 ), self.show )                       # The after function takes a time argument in miliseconds
        
    def show( self ):
        """
        Displays the ToolTip if the time delay has been long enough
        """
        if self.visible == 1 and time() - self.lastMotion > self.delay:
            self.visible = 2
        if self.visible == 2:
            self.deiconify()
            
    def move( self, event ):
        """
        Processes motion within the widget.
        
        Arguments:
          event: The event that called this function
        """
        self.lastMotion = time()
        if self.follow == False:                                                # If the follow flag is not set, motion within the widget will make the ToolTip dissapear
            self.withdraw()
            self.visible = 1
        self.geometry( '+%i+%i' % ( event.x_root+10, event.y_root+10 ) )        # Offset the ToolTip 10x10 pixes southwest of the pointer
        try:
            self.msgVar.set( self.msgFunc() )                                   # Try to call the message function.  Will not change the message if the message function is None or the message function fails
        except:
            pass
        self.after( int( self.delay * 1000 ), self.show )
            
    def hide( self, event=None ):
        """
        Hides the ToolTip.  Usually this is caused by leaving the widget
        
        Arguments:
          event: The event that called this function
        """
        self.visible = 0
        self.withdraw()


def xrange2d( n,m ):
    """
    Returns a generator of values in a 2d range
    
    Arguments:
      n: The number of rows in the 2d range
      m: The number of columns in the 2d range
    Returns:
      A generator of values in a 2d range
    """
    return ( (i,j) for i in xrange(n) for j in xrange(m) )


def range2d( n,m ):
    """
    Returns a list of values in a 2d range
    
    Arguments:
      n: The number of rows in the 2d range
      m: The number of columns in the 2d range
    Returns:
      A list of values in a 2d range
    """
    return [(i,j) for i in range(n) for j in range(m) ]


def print_time():
    """
    Prints the current time in the following format:
    HH:MM:SS.00
    """
    t = time()
    timeString = 'time='
    timeString += strftime( '%H:%M:', localtime(t) )
    timeString += '%.2f' % ( t%60, )
    return timeString
    
def main():
    root = Tk()
    btnList = []
    for (i,j) in range2d( 6, 4 ):
        text = 'delay=%i\n' % i
        delay = i
        if j >= 2:
            follow=True
            text += '+follow\n'
        else:
            follow = False
            text += '-follow\n'
        if j % 2 == 0:
            msg = None
            msgFunc = print_time
            text += 'Message Function'
        else:
            msg = 'Button at %s' % str( (i,j) )
            msgFunc = None
            text += 'Static Message'
        btnList.append( Button( root, text=text ) )
        ToolTip( btnList[-1], msg=msg, msgFunc=msgFunc, follow=follow, delay=delay)
        btnList[-1].grid( row=i, column=j, sticky=N+S+E+W )
    root.mainloop()
    
if __name__ == '__main__':
    main()

相關推薦

python3使用tkinter介面滑鼠提示(ToolTip)

from tkinter import * from time import time, localtime, strftime class ToolTip( Toplevel ):     """     Provides a ToolTip widget for Tki

python3使用tkinter介面按鈕Button

from tkinter import * class GUI:     def __init__(self):         self.root = Tk()         self.root.title('Button Styles')         for bd

USB驅動程式滑鼠鍵盤

我們還是接著來看看我們的例子程式 usbmouse.c 這裡它接著判斷了他是不是滑鼠, 得到它的usb_host_interface,interface=intf->cur_alsetting就是當前介面的設定 這裡有個介面描述符,我們來看看介面描述符 介面

用MFC漂亮介面登入介面

前段時間由於工作原因,一直沒有更新部落格,今天,繼續講解如何用MFC做漂亮介面,前幾次我們講了如何美化視窗背景,如何美化標題,如何美化按鈕,今天我們用以前學過的知識來一起做一個登入介面,這個登入介面的效果圖如下:分析當我們看到這個介面的時候,先不要忙著去做,先要分析一下哪些是

JavaSwing圖形介面程式設計訊息提示框(二)

package three.day.frame; import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import java.awt.event

百度地圖自動提示--autoComplete

esp lan length aid time 下拉 html style log <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8">

Linux Bash編程錯誤提示

Linux Bash編程簡單操作你以為任何命令的執行錯誤都能報錯?你想多了,在Bash編程中,有很多命令錯誤提示是需要自己編寫的。下面就來一個首先比較參數的個數是否正確,正確的情況下在進行下一步。Linux Bash編程之錯誤提示

PHP開發APP介面封裝通訊介面

PHP開發APP介面之封裝通訊介面 按json方式輸出通訊資料 /** * 按json方式輸出通訊資料 * @param integer $code 狀態碼 * @param string $message 提示資訊 * @p

jquery Select2 學習筆記中文提示 - CSDN部落格

首先學習這個東西呢,還是看官網比較全面 select2官網例子   要select2中文顯示:必須要引入中文包,且一定要放在select2.js之後   [javascript]  view plain  copy

reidis分散式鎖介面防重放

需求: 隨著專案的發展壯大,也會引起一些外圍的大神,幫助測測併發,挑挑系統漏洞,以及宕機測試。這時候介面做防重放勢在必行,選用redis做鎖在合適不過,nosql資料庫 單執行緒的redis為什麼這麼快 (一)純記憶體操作 (二)單執行緒操作,避免了頻繁的上下文切換 (三)採用了非阻塞I/O多路

一步一步開始FPGA邏輯設計 - 高速介面PCIe(轉)

reference: https://blog.csdn.net/jackxu8/article/details/53288385   這篇文章主要針對Xilinx家V6和K7兩個系列的PFGA,在Linux和Windows兩種系統平臺下,基於Xilinx的參考案例XAPP1052的基

【學習筆記】 唐大仕—Java程式設計 第4講 類、包和介面4.2 類的繼承

【學習筆記】 唐大仕—Java程式設計 第4講 類、包和介面之4.2 類的繼承 super的使用 1.使用super訪問父類的域和方法 注意:正是由於繼承,使用this可以訪問父類的域和方法。但是有時為了明確指明父類的域和方法,就要用關鍵字super。this和super都是指當前同一個物件

【學習筆記】 唐大仕—Java程式設計 第4講 類、包和介面4.4 訪問修飾符

修飾符(modifiers) 訪問修飾符(access modifiers) 如public/private等 其他修飾符 如abstract等 可以修飾類、也可以修飾類的成員(欄位、方法)   同一個類中 同一個包中 不同包中的子類

如何使用postman介面測試

1、只要是get請求都可以在瀏覽器中直接發:   在訪問地址後面拼  ?key=value&key=value 例如:   在瀏覽器中直接輸入訪問地址,後面直接拼需要傳給伺服器的引數   http://api.nnzhp.cn/api/user/stu_info?st

【學習筆記】 唐大仕—Java程式設計 第4講 類、包和介面4.6 介面

【學習筆記】 唐大仕—Java程式設計 第4講 類、包和介面之4.6 介面 介面(interface) 介面,某種特徵的約定 定義介面interface  所有方法都自動是public abstract 實現介面implements  可以實現多繼承  與類的繼承關係無關 面向介面程式設計,而不

JS特效-滑鼠提示

1.分析效果實現原理   樣式:div 的 display   事件: onmouseover   移入       onmouseout 移出 2.特效基礎   事件驅動:onmouseover,onmouseout   元素屬性操作:obj.style.[屬性]

登入介面Axure原型製作

*****登入介面製作步驟***** 1、背景色:需要設定的背景色不知道色值,可以使用截圖工具擷取一小塊貼上到axure頁面, 點選頁面樣式中的背景色左上角的取色器點選一下該色塊,即可將背景色全部填充為需要的背景色。2、logo位置:直接使用截圖工具測量一下logo距離瀏覽器頂部的距離是多少,在頁面中點選圖

unity3d滑鼠控制人物移動

參考http://blog.csdn.net/a2587539515/article/details/9390795博文 實現其實很簡單,用到navigation  第一步獲取滑鼠點選的世界座標 第二步,移動到改座標點 程式碼如下: Vector3 poin

C# 公共控制元件progressBar、 toolTip

1、窗體中加入控制元件progressBar1,  toolTip1,timer1 和三個button 2、程式碼如下: private void button1_Click(object sender, EventArgs e)//開始 { timer1.

怎樣用JMeter介面測試?

本文介紹JMeter如何做web service測試,一般來說web服務,一般指的是HTTP請求相關的內容。這裡就介紹一下如何利用JMeter做基於HTTP的web介面測試。介面也叫API(Application Programming Interface),很多我們使用的各種APP,上面的內容顯示大部分都呼