Tkinter子窗口/父窗口管理

huangapple go评论96阅读模式
英文:

Tkinter chlid / parrent window management

问题

我有困难使tkinter的行为符合以下所有条件,当从父窗口的操作创建子窗口时:

  • 焦点在子窗口上
  • 禁用与父窗口内容的交互
  • 允许用户使用父窗口右上角的默认退出按钮关闭父窗口(这个操作也应该关闭子窗口)

我尝试过child.transient(root)child.grab_set(),但它们都不像我希望的那样工作。

英文:

I have trouble making tkinter behaviour to meet the all of the conditions below when creating child window from action on the parent window:

  • focus on child window
  • disable interaction with parent window content
  • enable user to close parent window with default exit button in right upper corner of parent window (that action should also close child window)

I have tried child.transient(root) and child.grab_set() but none of them work as I would like it to.

from tkinter.ttk import *

master = Tk()
master.geometry("200x200")
 

def openNewWindow():
    newWindow = Toplevel(master)
    newWindow.geometry("200x200")
    Label(newWindow,
          text ="This is a new window").pack()
    newWindow.grab_set()
 
 
label = Label(master,
              text ="This is the main window")
label.pack(pady = 10)

btn = Button(master,
             text ="Click to open a new window",
             command = openNewWindow)
btn.pack(pady = 10)

mainloop() 

答案1

得分: 1

在OSX上,使用grab_set似乎可以实现你想要的效果。它应该在所有平台上都起作用,尽管我没有能力在其他平台上进行测试。

在下面的示例中,你可以单击主窗口上的按钮以创建一个新窗口。当新窗口打开时,你不能再次单击主窗口上的按钮。但你仍然可以使用标题栏上的关闭按钮关闭主窗口。

import tkinter as tk

def new_window():
    top = tk.Toplevel(root)
    entry = tk.Entry(top)
    entry.pack(fill="x", padx=20, pady=20)
    entry.focus_set()
    top.grab_set()

root = tk.Tk()
button = tk.Button(root, text="new window", command=new_window)
button.pack(padx=20, pady=20)

root.mainloop()
英文:

On OSX, using grab_set seems to do exactly what you want. It should work the same on all platforms, though I don't have the ability to test it on any other platforms.

In the following example you can click a button on the main window to create a new window. When that new window is open, you cannot click the button in the main window again. You're still able to close the main window with the close button on the title bar.

import tkinter as tk

def new_window():
    top = tk.Toplevel(root)
    entry = tk.Entry(top)
    entry.pack(fill="x", padx=20, pady=20)
    entry.focus_set()
    top.grab_set()

root = tk.Tk()
button = tk.Button(root, text="new window", command=new_window)
button.pack(padx=20, pady=20)


root.mainloop()

huangapple
  • 本文由 发表于 2023年3月3日 22:52:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628576.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定