Tkinter:将simpledialog.askinteger放在顶层框中

时间:2017-12-15 14:06:41

标签: python tkinter toplevel simpledialog

我在顶级小部件中使用simpledialog小部件时遇到问题。下面的代码提取导致一个空的弹出窗口(标题为" Blocked fields"),第二个弹出窗口,其中包含正确的simpledialog(也正常工作)和主游戏窗口(此处未显示)代码)。

我想摆脱第二个过时的窗口,我认为它必须是一件简单的事情,但我被困住了(如果你不能告诉已经完成python新手)。任何提示高度赞赏!

import tkinter as tk
from tkinter import simpledialog

root = tk.Tk()
root.geometry("580x400+300+200")
root.title("Pah Tum")

#Popup window
block_request_top = tk.Toplevel()
block_request_top.title("Blocked fields")
entry_block = simpledialog.askinteger("Blocked fields", \
"Please enter a number of fields to be blocked. Choose an \
uneven number between 5,13]", parent=block_request_top, minvalue=5, \
maxvalue=13)

2 个答案:

答案 0 :(得分:0)

针对此特定问题实现此问题的最简单方法可能是使用withdrawiconifydeiconify方法,在它们之间创建entry_block,如下所示:

...
block_request_top.withdraw()

entry_block = simpledialog.askinteger("Blocked fields", \
"Please enter a number of fields to be blocked. Choose an \
uneven number between 5,13]", parent=block_request_top, minvalue=5, \
maxvalue=13)

block_request_top.iconify()
block_request_top.deiconify()

整个代码:

import tkinter as tk
from tkinter import simpledialog

root = tk.Tk()
root.geometry("580x400+300+200")
root.title("Pah Tum")

#Popup window
block_request_top = tk.Toplevel()
block_request_top.title("Blocked fields")

block_request_top.withdraw()

entry_block = simpledialog.askinteger("Blocked fields", \
"Please enter a number of fields to be blocked. Choose an \
uneven number between 5,13]", parent=block_request_top, minvalue=5, \
maxvalue=13)

block_request_top.iconify()
block_request_top.deiconify()

我非常怀疑这是你最终会最终使用的。

答案 1 :(得分:0)

您根本不需要Toplevel()窗口。 askinteger()是一个对话框,不需要容器小部件。只需跳过block_request_top窗口代码即可。

import tkinter as tk
from tkinter import simpledialog

root = tk.Tk()
root.geometry("580x400+300+200")
root.title("Pah Tum")

# Popup window
#block_request_top = tk.Toplevel()
#block_request_top.title("Blocked fields")
entry_block = simpledialog.askinteger("Blocked fields",
"Please enter a number of fields to be blocked. Choose an \
uneven number between 5,13]", parent=root, minvalue=5, # parent changed...
maxvalue=13)
print('Okay, I will block %d fields.' % entry_block) # new, to see value
# set up the rest of your GUI
root.mainloop() # You need this for the GUI to remain alive.

父级的值已更新为root,以反映Toplevel窗口消失。

最后还需要root.mainloop()调用,以保持GUI处于活动状态并运行。一旦你的程序到达这里,Tkinter系统基本上只是等待“事件”发生,比如用户点击按钮或键入字段。您仍然必须将所有这些与您必须绘制的所有按钮绑在一起。有几个人发布了同样的问题。