按钮错误,但我得到IndexError:列表索引超出范围

时间:2018-08-12 00:45:18

标签: python tkinter python-3.6

我的界面上有两个按钮。我希望它们都可以在单击它们或单击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 Key为一个按钮或另一个按钮赋予 focus 时,不会发生这种情况。即使焦点位于准备按钮上,当您按下Enter时,也会得到:程序启动

1 个答案:

答案 0 :(得分:0)

这是解决我的问题的方法。 我希望它可以帮助其他与我有相同问题的人。

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

祝你有美好的一天! :)