【问题标题】:Unknown syntax error on creating a simple widget in Tkinter在 Tkinter 中创建简单小部件时出现未知语法错误
【发布时间】:2011-11-25 22:58:37
【问题描述】:

我正在按照本教程 (http://sebsauvage.net/python/gui/#add_button) 使用 Tkinter 制作小部件。我一直确保非常仔细地遵循它,但是,当我现在在第 10 步中运行它时,我收到“无效语法”错误。代码如下:

import tkinter

class simpleapp_tk(tkinter.Tk):
    def __init__(self,parent):
        tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()

        self.entry = tkinter.Entry(self)
        self.entry.grid(column=0,row=0,sticky='EW')

        button = tkinter.Button(self,text=u"Click me !")
        button.grid(column=1,row=0)

if __name__ == "__main__":
    app = simpleapp_tk(None)
    app.title('my application')
    app.mainloop()

IDLE指出错误在这一行,选中第二个引号:

button = tkinter.Button(self,text=u"Click me !**"**)

本教程是用 Python 2 编写的,但我使用的是 Python 3。谁能看到错误是什么以及如何修复它(在 Python 3 中)?

提前感谢您的帮助,我是编程新手,英语不是我的母语。

【问题讨论】:

  • 为什么在 Python 3 中使用u"string"?在 Python 3 中,所有字符串始终是 Unicode。

标签: python python-3.x tkinter syntax-error


【解决方案1】:

u"Click me !**" 替换为"Click me !**"

u 在 Python 2 中表示 Unicode 字符串(键入 unicode 而不是 str),但在 Python 3 中,strunicode 类型之间的区别消失了,u已报废。

【讨论】:

  • 这并不完全正确。 Python 2 中的 str 对象的行为接近 Python 3 中的 bytes
  • @patrys: 是的,所以现在bytesstr 之间有了区别,但strunicode 之间的区别仍然没有了;从文本处理的角度来看,这是主要的变化。
  • 我的意思是,目前的情况最好描述为“str 被重命名为 bytes,带有 b 前缀,unicode 被重命名为 str 失去了 @987654340 @前缀”。
【解决方案2】:

Python 3 中没有用于 unicode 字符串的 u 前缀。

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    相关资源
    最近更新 更多