python - 为什么我的 python 编辑器不能工作

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

最佳答案

更好的是:

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

但是您可能希望将您的功能直接插入按钮小部件,这里不需要绑定(bind),它可以与标签小部件一起使用,例如:

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

("Button-1"是鼠标左键点击事件的名字,不是widget变量名)

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

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

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

就像我说的,像这样的绑定(bind)对于另一个小部件可能有意义:

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

关于python - 为什么我的 python 编辑器不能工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46026728/

相关文章:

python - 如何在 Tkinter 中设置窗口的背景图像

python tkinter Canvas 'transparent'

python - 在 Tkinter 窗口中调用包含 'time.sleep()' 的外部函数

python - 使用python从文本文件中提取细节

python - ujson 无法编码 numpy 数组

python - python 中链表实现的合并排序不起作用

python - 使用 ElementTree 从头开始​​创建 xml 文档

python - opencv python中的渐变蒙版混合

python - 使用带有 tkinter 输入 GUI 形式的内部函数结束正在运行的函数,并在退出 GUI 时显示警告消息

python - 检查顶层窗口是否关闭?