为什么我的python编辑器不起作用

时间:2017-09-03 18:41:15

标签: python tkinter

我下载了pycharm,我将一些代码从youtube教程复制到了制作视频的人手中,但是当我尝试运行它时它没有用,这就是它所说的:

C:\Python27\python.exe C:/Python27/Lib/site-packages/wheel/test/test245425232.py
Traceback (most recent call last):
  File "C:/Python27/Lib/site-packages/wheel/test/test245425232.py", line 9, in <module>
    button1.bind("<button1>", printName)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1098, in bind
    return self._bind(('bind', self._w), sequence, func, add)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1053, in _bind
    self.tk.call(what + (sequence, cmd))
_tkinter.TclError: bad event type or keysym "button1"

Process finished with exit code 1

以下是代码:

from tkinter import *

root=Tk()

def printName():
    print("hi stuff")

button1=Button(root, text="print my name")
button1.bind("<button1>", printName)
button1.pack()
root.mainloop()

1 个答案:

答案 0 :(得分:4)

最好用:

button1.bind("<Button-1>", printName)

但您可能希望将函数直接插入按钮小部件,此处不需要绑定,例如对标签小部件有用:

button1=Button(root, text="print my name", command=printName)

(“Button-1”是鼠标左键单击事件的名称,而不是窗口小部件变量名称)

否则,您需要使用参数声明函数printName:绑定给出的事件。

def printName(event):
    print("hi stuff")

button1=Button(root, text="print my name")
button1.bind("<Button-1>", printName)

就像我说的那样,这样的绑定对于另一个小部件有意义:

from tkinter import *

root=Tk()

def printName(event):
    print("hi stuff")

label1=Label(root, text="print my name")
label1.bind("<Button-1>", printName)
label1.pack()
root.mainloop()