Tkinter (20) 顶层窗口部件 Toplevel

顶层窗口部件的创建及其选项

可单独存在的顶层窗口, 具有独立的窗口管理器, 可以独立移动和调整大小, 应用程序可以使用任意数量的顶级窗口. 任可部件都可以使用 winfo_toplevel() 方法返回其顶层窗口部件.

top_level = tk.Toplevel(option, ...)
选项 说明
bg or background 背景色
bd or borderwidth 外框寛度, 内定为 0
class_ 分类名
cursor 当鼠标移到部件处时,所显示的鼠标图示
height 窗口高度
highlightbackground 非聚焦时的聚焦颜色
highlightcolor 聚焦时的聚焦颜色
highlightthickness 聚焦厚度, 内定 1, 0 则无
menu 菜单部件
padx 部件左右间隔, 内定为 0 点素
pady 部件上下间隔, 内定为 0 点素
relief 外框花样
takefocus 一般来说, 窗口不会聚焦, 设 True 可聚焦
width 窗口寛度

顶层窗口部件的方法

方法 说明
aspect(nmin, dmin, nmax, dmax) 限制窗口寛度与长度的比例 [nmin/dmin, nmax/dmax]
deiconify() 还原图标化的窗口
geometry(newGeometry=None) 设置或还原窗口的大小及位置字符串
iconify() 图标化窗口
lift(aboveThis=None) 上移窗口到最顶层或某一窗口上一层
lower(belowThis=None) 下移窗口到最底层或某一窗口下一层
maxsize(width=None, height=None) 设置或返回窗口最大尺寸
minsize(width=None, height=None) 设置或返回窗口最小尺寸
overrideredirect(flag=None) 设置重写重定向标志(override redirect) 为True, 窗口上方的窗口管理器会被移除, 因此窗口管理就不能移动, 改变大小, 图标化, 关闭窗口. 设置为False 就可以还原; 无参数则返回目前的设置值. 在设置该参数时, 要记得先调用update_idletasks() 方法; 如果在进入mainloop() 之前调用它,则窗口将在显示之前被禁用; 在某些Unix 及MacOS 平台可能不适用
resizable(width=None, height=None) 设置窗口的尺寸可否调整, 或返回窗口可否调整尺寸的 2-tuple 值
state(newstate=None) 设置或返回目前窗口的状态, ‘normal’/‘iconic’/‘withdraw’
title(text=None) 设置或返回窗口的标题
transient(parent=None) 设置该窗口作为某父窗口的过渡窗口, 内定为该窗口的父窗口. 过渡窗口会在其父窗口之前, 如果父窗口被图标化, 则它也会被图标化
withdraw() 隐藏视窗, 可以 deiconify() 或 iconify() 方法来还原

范例视窗及代码

Python

import tkinter as tk

def win(text, width, height):
    top_level = tk.Toplevel()
    top_level.title(f'{width}x{height}')
    label = tk.Label(
        top_level, text=text, width=width, height=height,
        wraplength=width*8, anchor=tk.NW, justify=tk.LEFT, borderwidth=5,
        relief=tk.SOLID)
    label.grid(row=0, column=0)
    return top_level, label

root = tk.Tk()
root.wm_title("Toplevel Demo")

font = ('Courier New', 16, 'bold')
t = ('This tutorial introduces the reader informally to the basic '
     'concepts and features of the Python language and system. It '
     'helps to have a Python interpreter handy for hands-on experience'
     ', but all examples are self-contained, so the tutorial can be '
     'read off-line as well.')

win1, label1 = win(t, 100, 20)
win2, label2 = win(t,  80, 25)
win3, label3 = win(t,  60, 35)
win4, label4 = win(t,  50, 40)

root.mainloop()
本作品采用《CC 协议》,转载必须注明作者和本文链接
Jason Yang
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!