How to get an input from the user and execute the input as a python code(sql) in tkinter?

Viewed 123

I searched for this but problem a lot but still couldn't figure it out yet. I will try to keep it simple.

I have this code , which is basically a Text box and submit button , the user will write a python code in the Text box ( the code is to alter or change a certain table or database in sqlite3) and after hitting submit the code the user wrote should be executed.

example of a code the user will write in the Text box :

insert into employee(id,first_name,last_name,password)
values (456,'test','tesst','testpass')

I will show you the code I have so far :

        admin_window = tk.Toplevel(root)
        admin_window.title('Admin Window')
        admin_window.geometry("450x450")
        sql_commands = tk.Text(admin_window)
        sql_commands.place(height=350, width=350,relx=0.5, rely=0.5, anchor='center')
        submit_button = tk.Button(admin_window, text=' Submit ', command=submit_click)
        submit_button.place(anchor='center',y=200,relx=0.5, rely=0.5,)

as you can see there is a Text box ( the text box is in a new window not in the root )

when the user press submit this is how I can get the input from him:

input = sql_commands.get("1.0",'end')

it return the input correctly, but the type is weird , the type is bunch of number then str at the end.

How can I take the input to execute it and treat it like a code? is this even a proper way do it ?

1 Answers

This works for me:

import tkinter as tk


def submit_click():
    exec(sql_commands.get("1.0", 'end'))


root = tk.Tk()

admin_window = tk.Toplevel(root)
admin_window.title('Admin Window')
admin_window.geometry("450x450")
sql_commands = tk.Text(admin_window)
sql_commands.place(height=350, width=350, relx=0.5, rely=0.5, anchor='center')
submit_button = tk.Button(admin_window, text=' Submit ', command=submit_click)
submit_button.place(anchor='center', y=200, relx=0.5, rely=0.5,)

root.mainloop()

The type seems normal on my end, just a string. You shouldn't use 'input' however as that is a built-in function in python.

The exec() function is also a built-in, and it executes a string as python code. Short guide on exec here

Related