Python中的focus_set()在第二个窗口中不起作用

时间:2015-01-18 15:00:38

标签: python python-3.x tkinter

getinput窗口出现在介绍窗口之后,应该专注于输入空间,但不是。如果我跳过介绍窗口,则会发生焦点。如果我然后输入1-10范围之外的数字,getinput窗口会重新出现,但没有焦点。有人可以帮忙吗?

用Python 3.3.5编写

import tkinter

def intro(tkinter):
    global contents
    w = 300
    h = 200
    frame = tkinter.Frame(root,width=w,height=h)
    frame.pack()
    label = tkinter.Label(frame,font=('courier', 12, 'bold'),\
        text="\nPlease click on OK.\n\n")
    label.pack()
    label.place(x=40,y=50)
    OK = tkinter.Button(root,bd=5,text='OK',font=('courier', 20, 'bold'),\
        command=root.destroy)
    OK.pack()
    OK.place(x=125,y=120)
    root.mainloop()

def cancel():
    global level
    level = contents.get()
    root.destroy()

def getinput(tkinter):
    global contents
    w = 400
    h = 300
    frame = tkinter.Frame(root,width=w,height=h)
    frame.pack()
    label = tkinter.Label(frame,font=('courier', 12, 'bold'),\
        text="Please enter a number in the\n range 1 to 10 and click on OK.")
    label.pack()
    label.place(x=40,y=50)
    entry = tkinter.Entry(frame,font=('courier', 24, 'bold'))
    entry.pack()
    entry.place(x=175,y=150,width=50)
    contents = tkinter.StringVar()
    contents.set("")
    entry["textvariable"] = contents
    entry.focus_set()       #Gives focus by flashing cursor in entry space.
    OK = tkinter.Button(root,bd=5,text='OK',font=('courier', 20, 'bold'),\
        command=cancel)
    OK.pack()
    OK.place(x=170,y=210)
    root.mainloop()

level = ""
contents = ""
root = tkinter.Tk()     #Comment out this line
intro(tkinter)          #and this line to skip intro window
root = tkinter.Tk()
getinput(tkinter)
while (int(level) < 1) or (int(level) > 10):
    root = tkinter.Tk()
    getinput(tkinter)

print('Result is ',level)

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。感谢@fhdrsdg,entry.focus_force()指出了这一点。下面是一个示例。

from tkinter import *
root = Tk()
Window = Frame(root)
Window.pack()
txt = Entry(Window)
txt.pack()
txt.focus_set()
root.mainloop()

root = Tk()
Window = Frame(root)
Window.pack()
txt = Entry(Window)
txt.pack()
txt.focus_force()
root.mainloop()