Skip to main content
 首页 » 编程设计

Python TksimpleDialog 定位在根窗口旁边

2024年10月17日9rubylouvre

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

我检查过这个link而且似乎没有任何简单对话框的定位参数。我也尝试过使用顶层,但打开多个窗口时它变得很乱。

我的代码如下:

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() 

请您参考如下方法:

一种方法是使用 Toplevel 小部件。而且一点也不乱。无论如何,要将输入框架放在您想要的位置,您必须首先设置主(根)框架的尺寸和位置:

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() 

这是将用户输入窗口放置在您想要的位置的示例。您需要实现它来验证和存储用户输入,并根据需要为尽可能多的用户实现。