如何在Tkinter中传递变量?附SQL Server连接示例代码
Hey there! Let's tackle how to pass that JobNo from your Tkinter input box to your SQL Server operations. I'll share a modified version of your code that ties everything together, then break down the key parts so you understand how it works.
Modified Full Code
import tkinter as tk import pyodbc def fetch_scrap_data(): # Grab the JobNo from the input field (clean up extra spaces) job_no = entry_job.get().strip() if not job_no: print("Please enter a valid JobNo first!") return # Database connection credentials server = 'svr' database = 'db' username = 'sa' password = 'password' try: # Establish connection to SQL Server conn = pyodbc.connect( f'DRIVER={{ODBC Driver 13 for SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}' ) print("Successfully connected to SQL Server!") # Create cursor and run query with the JobNo variable cursor = conn.cursor() # Use parameterized query to avoid SQL injection (critical security practice) sql_query = "SELECT * FROM ScrapReports WHERE JobNo = ?" cursor.execute(sql_query, (job_no,)) # Fetch and display results (customize this part based on your needs) results = cursor.fetchall() if results: print(f"Scrap data for JobNo {job_no}:") for row in results: print(row) else: print(f"No scrap records found for JobNo {job_no}") # Clean up resources cursor.close() conn.close() except Exception as e: print(f"Oops, something went wrong: {str(e)}") # Set up the Tkinter window root = tk.Tk() root.title("Scrap Report") root.geometry('400x400') # Add label and input box for JobNo label_job = tk.Label(root, text='Enter JobNo') label_job.pack(pady=10) entry_job = tk.Entry(root, width=30) entry_job.pack(pady=5) # Add button to trigger data fetch (this is where variable passing starts) btn_fetch = tk.Button(root, text="Get Scrap Data", command=fetch_scrap_data) btn_fetch.pack(pady=20) # Start the Tkinter main loop root.mainloop()
Key Breakdown of the Variable Passing Logic
- Grabbing User Input: We added a button that triggers the
fetch_scrap_datafunction when clicked. Inside this function,entry_job.get()pulls the text from the input field—strip()ensures we don't accidentally pass extra spaces as part of the JobNo. We also check if the input is empty to avoid useless database calls. - Safe Variable Passing to SQL: Instead of concatenating the JobNo directly into the SQL string (which is a huge security risk for SQL injection), we use a parameterized query with the
?placeholder. We pass thejob_noas a tuple tocursor.execute(), which safely maps the variable to the query. - Connection Management: In this example, we connect to the database each time the button is clicked—perfect for short, simple apps. If your app runs continuously, you could move the connection setup outside the function (like when the window loads) and reuse the connection, just remember to handle disconnections gracefully.
- Error Handling: The
try-exceptblock catches common issues (bad credentials, missing input, database downtime) and prints a readable error message, so you don't have to debug a crashed app.
内容的提问来源于stack exchange,提问作者RBC Kyle Bullard
相关产品推荐
相关产品推荐

