可以通过多种方式将音量悬停在窗口上,您也可以悬停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()