【问题标题】:Button error, but I get IndexError: list index out of range按钮错误,但我得到 IndexError: list index out of range
【发布时间】:2018-08-12 00:45:18
【问题描述】:

我的界面上有两个按钮。当我点击它们或点击Enter Key时,我希望它们都能够调用它们各自的函数。
我遇到的问题是,当我点击Enter Key 时,只有遍历focus 中的最后一个按钮被激活,即使前面的按钮具有focus。我可以做些什么来解决这个问题。
欢迎和赞赏有用的答案。

这是有问题的问题:

from tkinter import *

w = Tk()

def startProgram(event = None):
    print('Program Starting')

def readyContent(event = None):
    print('Content being prepared')

# Buttons
Button(text='Prepare', command=readyContent).grid(row=10,column=2)
w.bind('<Return>',readyContent) # Binds the Return key to a Function
Button(text='Start', command=startProgram).grid(row=10,column=3)
w.bind('<Return>',startProgram) # Binds the Return key to a Function

w.mainloop()

当您点击准备开始按钮时,您会得到正在准备的内容程序启动强>分别。当您使用 Tab Keyfocus 赋予一个按钮或另一个按钮时,不会发生类似的情况。即使 焦点 位于 Prepare 按钮上,当您点击 Enter 时,您会得到:程序启动

【问题讨论】:

  • 哪个按钮有焦点在这里完全无关紧要,因为您没有将任何东西绑定到各个按钮。
  • 请包含您的错误的完整回溯,以便我们确定哪一行是问题
  • @jasonharper - 感谢两位的输入。我是 Tkinter 的新手。我以为我必须将函数绑定到窗口。在另一个项目中,我只有一个按钮,我想这就是为什么这个公式可以顺利运行的原因。当我不得不处理按钮时,全景图发生了变化。谢谢你的评论。如果有人遇到同样的问题,我将发布解决方案。再次感谢。

标签: python tkinter python-3.6


【解决方案1】:

这是我的问题的解决方案。 我希望它可以帮助其他和我有同样问题的人。

from tkinter import *

w = Tk()

def startProgram(event = None):
    print('Program Starting')

def readyContent(event = None):
    print('Content being prepared')

# Buttons
btn1 = Button(text='Prepare', command=readyContent)
btn1.grid(row=10,column=2)
btn1.bind('<Return>',readyContent) # Binds the Return key to a Function
btn2 = Button(text='Start', command=startProgram)
btn2.grid(row=10,column=3)
btn2.bind('<Return>',startProgram) # Binds the Return key to a Function

w.mainloop()

祝你有美好的一天! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 2020-10-27
    • 2020-10-16
    • 2019-02-23
    • 1970-01-01
    相关资源
    最近更新 更多