Python TksimpleDialog定位在根风旁边

2024-09-30 22:12:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图打开一个简单的对话框窗口,在这个窗口中,用户根据根窗口上显示的菜单输入一个选项。但是,当我运行代码时,对话框会直接在根窗口的菜单上方打开,使它看不见。是否有方法打开对话框,使其在根窗口旁边打开,如所附图像所示。在

enter image description here

我检查了这个link,它似乎没有任何简单对话框的定位参数。我也试过用toplevel,但由于打开了多个窗口,它变得一团糟。在

我的代码如下:

from Tkinter import *
import tkSimpleDialog

root = Tk()
root.lift()


Label(root, text = "Menu Choices:").grid(row=1, column =0)
Label(root, text='1. Baloney and cheese').grid(row=2, column=0, pady=4)
Label(root, text='2. Roast chicken and gravy').grid(row=3, column=0, pady=4)
Label(root, text='3. Pear salad').grid(row=4, column=0, pady=4)
Label(root, text='4. Cateloupe and brocoli soup').grid(row=5, column=0, pady=4)

people = ["Liam","Henry","Paula"]

menuChoice = []

for i in people:
    c = tkSimpleDialog.askinteger('Franks Restaurant', 'Please choose your meal?', parent = root)
    menuChoice.append(c)

root.mainloop()

Tags: and代码textimport菜单columnrootpeople
2条回答

一种方法是使用顶级小部件。一点也不乱。无论如何,要将输入框放置在所需的位置,必须首先设置主(根)帧的尺寸和位置:

from Tkinter import *
import ttk

root = Tk()
root.lift()
w = 300; h = 200; x = 10; y = 10
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

Label(root, text = "Menu Choices:").grid(row=1, column =0)
Label(root, text='1. Baloney and cheese').grid(row=2, column=0, pady=4)
Label(root, text='2. Roast chicken and gravy').grid(row=3, column=0, pady=4)
Label(root, text='3. Pear salad').grid(row=4, column=0, pady=4)
Label(root, text='4. Cateloupe and brocoli soup').grid(row=5, column=0, pady=4)

def store_entry():
  print "Entry stored as "+ent.get()

def exit_entry():
  print "Entry cancelled"
  top.destroy()

top = Toplevel()
top.title('Franks Restaurant')
top.geometry("%dx%d+%d+%d" % (w, h, w+x+20, y))
Label(top, text='Please choose your meal').place(x=10,y=10)
ent = Entry(top); ent.place(x=10, y=50); ent.focus()
Button(top, text="OK", command=store_entry).place(x=10, y=150) 
Button(top, text="Cancel", command=exit_entry).place(x=60, y=150)  

root.mainloop()

这是一个将用户输入窗口放置在您想要的位置的示例。您需要实现它来验证和存储用户输入,并为您需要的任意多个用户提供支持。在

Tk库实际上有一个函数可以实现这一点,尽管它名义上是“私有的”。您可以按如下方式使用它。在

import tkinter as tk

root = tk.Tk()
root.wm_geometry("800x600")
dialog = tk.Toplevel(root)
root_name = root.winfo_pathname(root.winfo_id())
dialog_name = dialog.winfo_pathname(dialog.winfo_id())
root.tk.eval('tk::PlaceWindow {0} widget {1}'.format(dialog_name, root_name))
root.mainloop()

这将把你的对话框放在指定窗口的中心(在本例中是根窗口)。在

相关问题 更多 >