简体   繁体   English

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

[英]Button error, but I get IndexError: list index out of range

I have two buttons on my interface. 我的界面上有两个按钮。 I want both of them to be able to call their respective functions when I either click on them or a hit the Enter Key . 我希望它们都可以在单击它们或按Enter Key时调用它们各自的功能。
The problem I'm having is that only the last button in the traveral focus gets activated when I hit the Enter Key , even if the preceeding one has the focus . 我遇到的问题是,只有在traveral 焦点最后一个按钮被激活时,我打了Enter Key ,即使在前述一个具有焦点 What can I do to resolve this problem. 我该怎么办才能解决此问题。
Useful answer are welcome and appreciated. 欢迎和赞赏有用的答案。

This is the problem in question: 这是有问题的问题:

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

When you click on the Prepare or Start button, in return you get either Content being prepared or Program Starting repectively. 当您单击“ 准备”或“ 开始”按钮时,相应地您将获得正在准备的内容或“ 程序 正在 启动” Nothing like that happens when you use the Tab Key to give focus to one button or the other. 当您使用Tab Key焦点移至一个按钮或另一个按钮时,不会发生任何类似的事情。 Even if the focus is on the Prepare button, when you hit Enter you get: Program Starting 即使焦点在“ 准备”按钮上,当您Enter时,您也会得到: 程序启动

This is the solution to my problem. 这是我的问题的解决方案。 I hope it helps anyone else having the same problem as me. 我希望它可以帮助其他与我有相同问题的人。

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

Have a good day! 祝你有美好的一天! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM