特定于 Windows 的解决方案
第一个选择是让你的窗口toplevel
瞬态窗口root
,这是一个非常简单的解决方案。
您需要做的就是将线路更改tp.attributes("-toolwindow", 1)
为tp.transient(root)
!
第二种选择更复杂,但在 Windows 系统中更通用。
Windows 系统中的每个窗口都有自己的样式,它表示为位样式的逻辑析取。您可以从头开始构建新样式,也可以将新样式设置为与旧样式分离(将其打开)或将旧样式与位样式的否定结合(将其关闭) :
- 要关闭最小化/最大化:
new style = old style AND NOT Maximize AND NOT Minimize
- 要打开最小化/最大化:
new style = old style OR Maximize OR Minimize
对于所有这些交互,我们需要ctypes库(python 附带)和一组 WinAPI 函数:
检查这个例子:
import tkinter as tk
import ctypes
# shortcuts to the WinAPI functionality
set_window_pos = ctypes.windll.user32.SetWindowPos
set_window_long = ctypes.windll.user32.SetWindowLongPtrW
get_window_long = ctypes.windll.user32.GetWindowLongPtrW
get_parent = ctypes.windll.user32.GetParent
# some of the WinAPI flags
GWL_STYLE = -16
WS_MINIMIZEBOX = 131072
WS_MAXIMIZEBOX = 65536
SWP_NOZORDER = 4
SWP_NOMOVE = 2
SWP_NOSIZE = 1
SWP_FRAMECHANGED = 32
def hide_minimize_maximize(window):
hwnd = get_parent(window.winfo_id())
# getting the old style
old_style = get_window_long(hwnd, GWL_STYLE)
# building the new style (old style AND NOT Maximize AND NOT Minimize)
new_style = old_style & ~ WS_MAXIMIZEBOX & ~ WS_MINIMIZEBOX
# setting new style
set_window_long(hwnd, GWL_STYLE, new_style)
# updating non-client area
set_window_pos(hwnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED)
def show_minimize_maximize(window):
hwnd = get_parent(window.winfo_id())
# getting the old style
old_style = get_window_long(hwnd, GWL_STYLE)
# building the new style (old style OR Maximize OR Minimize)
new_style = old_style | WS_MAXIMIZEBOX | WS_MINIMIZEBOX
# setting new style
set_window_long(hwnd, GWL_STYLE, new_style)
# updating non-client area
set_window_pos(hwnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED)
def top():
tp = tk.Toplevel()
# tp.geometry('300x300')
# tp.iconbitmap('icon.ico')
hide_minmax = tk.Button(tp, text='hide minimize/maximize', command=lambda: hide_minimize_maximize(tp))
hide_minmax.pack()
show_minmax = tk.Button(tp, text='show minimize/maximize', command=lambda: show_minimize_maximize(tp))
show_minmax.pack()
root = tk.Tk()
root.geometry('400x400')
b = tk.Button(root, text='open window with icon', command=top)
b.pack()
root.mainloop()