我正在尝试使用从sql表中提取的数据在类的输入框中填充默认值,但是我遇到了麻烦。我将SQL查询拉到类之外,然后尝试使用全局变量访问类内的变量。然后,我使用set()在输入框中设置全局变量。我们对我所缺少的任何见解都深表感谢。编辑:我将此更新为反映建议的代码更改的更正的代码。该代码现在有效。

# Data Audit GUI
import pandas as pd
import numpy as np
import pandas.io.sql as psql
import pyodbc

from tkinter import *
from tkinter.ttk import *
root = Tk()

cnxn = pyodbc.connect("DRIVER={SQL Server};""SERVER=xxxx;DATABASE=xxxx;""trusted_connection=yes;")

sql = """
SELECT title
FROM dbo.jobtable
WHERE jobid=4001
"""
Job = psql.read_sql(sql, cnxn)
Pyjobtitle = StringVar()
Pyjobtitle = Job['title'].values[0]

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

    def create_widgets(self):

        global Pyjobtitle
        self.ClassJobTitle = StringVar()
        self.JobTitle = Entry(root, width = 45, text = self.ClassJobTitle) # Job Title
        self.JobTitle.grid(row = 2, column = 0, columnspan = 1, rowspan = 1, sticky = W)
        self.ClassJobTitle.set(Pyjobtitle)

app = Application(root)
root.mainloop()

最佳答案

好吧,psql.read_sql返回一个DataFrame,因此您需要在以下领域中做一些事情:

my_title = df['title'].values[0]

关于python - 在类中从sql填充输入框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43375908/

10-12 05:42