【问题标题】:Invalid syntax when inside class python v2.7 [closed]在类python v2.7中时语法无效[关闭]
【发布时间】:2015-08-23 14:43:08
【问题描述】:

当我尝试在我的类方法中运行 cursor.execute("SELECT VERSION()") 时,它给了我一个 SyntaxError。但在课堂外工作得很好,代码相同。我是 Python 的新手,尝试过搜索等,但找不到任何东西。

我得到的错误如下:

cursor.execute("SELECT VERSION()")
 ^
SyntaxError: invalid syntax

我尝试运行的代码如下:

try:
    # for Python2
    from Tkinter import *
except ImportError:
    # for Python3
    from tkinter import * 

import tkMessageBox
import MySQLdb

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self,master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        Label(self, text="Username").grid(row=0)
        Label(self, text="Password").grid(row=1)
        Label(self, text="Database").grid(row=2)
        self.username = Entry(self)
        self.username.grid(row=0, column=1)

        self.password = Entry(self)
        self.password.grid(row=1, column=1)

        self.database = Entry(self)
        self.database.grid(row=2, column=1)

        Button(self, text='Show', command=self.show_entry_fields).grid(row=3, column=1, sticky=W, pady=4)

    def show_entry_fields(self):
        try:
            db = MySQLdb.connect("localhost", "root", "", "python" )
            cursor = db.cursor()
            cursor.execute("SELECT VERSION()")
            data = cursor.fetchone()
            db.close()
        except:
            tkMessageBox.showinfo("Say Hello", "Dont work.")

root = Tk()
root.title("Simple GUI")
root.resizable(width = FALSE, height = FALSE)
root.geometry("700x500")

# Create the frame and add it to the grid
app = Application(root)

root.mainloop()

【问题讨论】:

  • 试过了,同样的错误。

标签: python tkinter mysql-python


【解决方案1】:

您混合了制表符和空格。 cursor.execute 行有 4 个空格而不是它应该有的一个制表符,导致缩进错位。在编辑器中打开“显示空白”以更轻松地查看此类内容。

【讨论】:

  • 你真神。谢谢你,现在工作正常!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
相关资源
最近更新 更多