窗内窗 [英] Window inside window
问题描述
我对 python 的 tkinter 不是很好,但我想知道是否有办法在窗口内创建一个窗口,该窗口不能离开主窗口的边界.
I'm not very good with tkinter of python, but i would like to know if theres a way to make a window inside a window, where that window cannot get out of the main window's bounds.
这是我当前的代码:
from tkinter import *
root = Tk()
root.title("Main Window")
root.geometry("640x480+100+100")
sub = Toplevel(root)
sub.title("Sub Window")
sub.geometry("320x240+125+125")
mainloop()
它看起来像这样:
我想知道如何隔离子窗口以将其保留在主窗口内,即使我将其拖出.
I would like to know how I can isolate the Sub Window to keep it inside the main window even if i drag it out.
非常感谢.
推荐答案
没有这样做的内置方法.但是我已经做了一个工作来适应它.请记住,当试图将子窗口移动到主窗口之外时,它不是一个平滑的锁,所以它会变得跳跃.另一个问题是,由于配置事件,我无法获得相对于主窗口的子窗口位置以在移动主窗口时保持它.仍在解决这个问题.但是,下面的代码确实有效,应该对您有用.
There is no built in method of doing so. However I've made a work around to accommodate it. Keep in mind that when trying to move the sub window outside the main window it isn't a smooth lock so it does get jumpy. Another issue is that because of the configure events I can't get the sub window position relative to main window to maintain it while moving the main window. Still working around that. However the code below does work and should be of use to you.
import tkinter as tk
root = tk.Tk()
root.title("Main Window")
root.geometry("640x480")
sub = tk.Toplevel(root)
sub.transient(root) #Keeps sub window on top of root
sub.title('Sub Window')
sub.minsize(320, 240)
sub.maxsize(320, 240)
pos = []
def main_move(event):
#When the main window moves, adjust the sub window to move with it
if pos:
sub.geometry("+{0}+{1}".format(pos[0], pos[1]))
# Change pos[0] and pos[1] to defined values (eg 50) for fixed position from main
def sub_move(event):
# Set the min values
min_w = root.winfo_rootx()
min_h = root.winfo_rooty()
# Set the max values minus the buffer for window border
max_w = root.winfo_rootx() + root.winfo_width() - 15
max_h = root.winfo_rooty() + root.winfo_height() - 35
# Conditional statements to keep sub window inside main
if event.x < min_w:
sub.geometry("+{0}+{1}".format(min_w, event.y))
elif event.y < min_h:
sub.geometry("+{0}+{1}".format(event.x, min_h))
elif event.x + event.width > max_w:
sub.geometry("+{0}+{1}".format(max_w - event.width, event.y))
elif event.y + event.height > max_h:
sub.geometry("+{0}+{1}".format(event.x, max_h - event.height))
global pos
# Set the current sub window position
pos = [event.x, event.y]
root.bind('<Configure>', main_move)
sub.bind('<Configure>', sub_move)
root.mainloop()
这篇关于窗内窗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!