【问题标题】:Python Tkinter IntVar Not UpdatingPython Tkinter IntVar 未更新
【发布时间】:2014-11-26 05:50:21
【问题描述】:

我有两个函数是 Python 3.4.1 Tkinter GUI 的一部分。

def jumpto():
    global jump
    jump = Tk()
    jump.wm_title("Jump")
    jump.focus_force()
    label = Label(jump, text = "Enter digit to jump:").pack()
    global jumptext
    jumptext = IntVar()
    jumpentry = Entry(jump, textvariable = jumptext)
    jumpentry.pack()
    jump.bind("<Return>", close)

def close(self):
    global jumptext
    global jump
    print(jumptext.get())
    while digit < jumptext.get(): #digit is an integer that increases in the unrelated area below
        #Do something completely unrelated
    jump.destroy()

jButton = Button(master, text = "JUMP", command = jumpto).pack() #master is the main Tk window

但是,当我运行代码时,close 中的jumptext.get() 仍然为 0,尽管在使用 jumpentry 创建的输入框中输入了一些内容。有什么方法可以使输入的信息实际更新为jumptext.get()

另外,如果有人能向我解释为什么 self 必须在 close 中输入,那将是一个奖励。

提前致谢!

【问题讨论】:

    标签: python-3.x tkinter


    【解决方案1】:

    问题是您创建了两个Tk() 实例,这会导致奇怪的行为。 jump 窗口应该是 Toplevel 窗口,如果您希望在 Tk() 窗口旁边有另一个窗口,则可以使用该窗口。

    close 需要接受一个参数,因为它由一个 bind 调用,它总是传递一个 event 对象,该对象包含有关触发 close 函数的事件的各种信息(例如鼠标位置和用于触发事件的键)。所以称它为event 而不是self 实际上会更正确。 self 是类中使用的变量,包含类属性。

    【讨论】:

    • 非常感谢!会+1,但我显然需要更多的代表。不过,令人惊叹的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多