【问题标题】:Toplevel window with hover on button and the toplevel window itself悬停在按钮上的顶层窗口和顶层窗口本身
【发布时间】:2019-10-06 08:09:06
【问题描述】:

我不喜欢 Python,为了练习,我尝试用 Tkinter 创建一个音频播放器 现在我正在尝试创建一个顶级窗口来更改音量,就像在许多播放器或浏览器中一样 基本思想和复杂性在于,当您将光标悬停在“按钮”上时,窗口应该出现,而当光标离开按钮和对话框本身时,窗口应该消失(例如:就像在 Youtube 上一样) 我知道,有一个像 Motion 或 Enter/Leave 这样的 Bind 事件。但是如何确保考虑到 Toplevel 小部件的空间,而不仅仅是按钮?

【问题讨论】:

  • 如果你将 "" 绑定到 Toplevel.deiconify() 并将 "" 绑定到 Toplevel.iconify() 也会为顶层窗口绑定相同的内容,因此当光标在窗口上时它不会在您没有将鼠标悬停在按钮或窗口本身上之前,请不要关闭。您可以使用它,例如将 '' 绑定到 Button 并将 '' 绑定到 Toplevel 窗口也可以解决问题。
  • 您的意思是...创建顶层窗口并让它一直存在?让他只用 bind 折叠和展开它?

标签: python python-3.x tkinter


【解决方案1】:

可以通过多种方式将音量悬停在窗口上,您也可以悬停Frame,而不是使用Toplevel 窗口,但使用Toplevel() 的想法为您提供了更多自定义选项并使其看起来更好就像我一样。

  • 我做了一个功能,可以通过Button.bind("<Enter>", change_volume)独立分配给任何按钮。

  • 在函数中,将在 ""destroy() 上相应地创建一个顶层窗口。

  • 我使用wm_overrideredirect(True) 删除了Toplevel 窗口中的装饰,例如窗口边缘的标题栏边框。

  • 我还使用了一点 -alpha 属性,通过attributes('-alpha', 0.6) 为窗口提供了一些透明度。

  • 1234563但它返回一个 float 值,而 Scale 正常返回 integer

结果:

_________(默认)_________ . ________(ttk 主题)________

..

代码示例:

from tkinter import *
from tkinter import ttk  # for round knob scale widget

root = Tk()
root['bg'] = 'lightyellow'
root.geometry('200x200+100+100')
volvar = IntVar(value=5)

def change_volume(evt=None):
    global vol_wid
    wid = evt.widget  # Get the widget the instance
    # Try / except to avoid errors like AttributeError.. 
    try: 
        # Returns if a window alrealy present
        if vol_wid.winfo_exists(): return 
    except: pass
    vol_wid = Toplevel(root)
    vol_wid.wm_overrideredirect(True)  # Removes the titlrbar and borders
    vol_wid.update()   # Don't need if not on macos
    vol_wid.lift()
    vol_wid.attributes('-alpha', 0.6) # Makes the window transparent
    vol_wid.attributes('-topmost', 1) # Be on top of every window
    scale = Scale(vol_wid, from_=0, to=10, variable=volvar, orient='horizontal', 
               bg='black', fg='white')    # NORMAL DEFAULT SCALE
    # scale = ttk.Scale(vol_wid, from_=0, to=10, variable=volvar, 
    #           orient='horizontal')    # ROUND KNOB SCALE
    scale.pack()
    # Set the window just above the button 
    width = int((scale.winfo_reqwidth() - wid.winfo_width()) / 2)
    vol_wid.geometry('+%s+%s' %(wid.winfo_rootx()-width, 
            wid.winfo_rooty()-scale.winfo_reqheight()))
    vol_wid.focus()  # Gives focus
    vol_wid.bind("<Leave>", lambda e: vol_wid.destroy()) # Bind to destroy window

Label(root, textvariable=volvar, font=('',16)).pack(pady=25)
B = Button(root, text='Volume',bg='lightpink', padx=10)
B.pack(pady=25)
B.bind("<Enter>", change_volume)
mainloop()

【讨论】:

    猜你喜欢
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多