@Fizl

Как использовать взятый с tk.Text текст в добавлении в БД?

Код
import tkinter as tk
import sqlite3
from tkinter import ttk
from functools import partial
class Main(tk.Frame):
    def __init__(self,root):
        super().__init__(root)
        self.db = db
        self.init_main()
        
       

    def init_main(self):
        lbl_main = tk.Label(text='TXT',fg='#336B87',font=('Modern',220),bg = '#2A3132')
        btn_database_workers = tk.Button(padx = 7,pady = 2, text = '', bg = '#336B87', 
                             activebackground = '#336B87',
                             compound = tk.TOP, font = ('Ubuntu', 72),bd = 10,command = self.open_database)
        lbl_main.pack()
        btn_database_workers.pack()
        
        lbl_main.place(x = 5,y = -45)
        btn_database_workers.place(x = 750,y = 45)

    def open_database(self):
        Child()

class Child(tk.Toplevel):
    def __init__(self):
        super().__init__(root)
        self.init_child()
        self.db = db
        self.db.cur = self.db.conn.cursor()
        self.view = app
        self.view_records()

    def init_child(self):
        self.title('Child')
        self.geometry('950x400')
        self['bg'] = '#2A3132' 
        self.resizable(False,False)

        self.entry1 = tk.Text(self,height = 2, width = 11,font = ('Ubuntu',15),bd = 5)
        self.entry1.pack()
        self.entry1.place(x = 3,y = 180)

        self.entry2 = tk.Text(self,height = 2, width = 11,font = ('Ubuntu',15),bd = 5)
        self.entry2.pack()
        self.entry2.place(x = 3, y = 245)

        self.tree = ttk.Treeview(self,column = ('clm1','clm2','clm3'),show = 'headings')
        self.tree.heading('#1', text = 'ID')
        self.tree.heading('#2', text = 'Name')
        self.tree.heading('#3', text = 'IP')
        self.tree.pack()



        delete_btn = tk.Button(self,text = 'Delete',padx = 25,pady = 10,font = ('Ubuntu',15),
                               bd = 8,bg = '#336B87',command = self.delete_records)
        delete_btn.pack()
        delete_btn.place(x = 0,y = 0)

        add_btn = tk.Button(self,text = 'Add',padx = 36,pady = 10,font = ('Ubuntu',15),bd = 8,bg = '#336B87')
        add_btn.pack()
        add_btn.place(x = 0,y = 75)
        add_btn.bind('<Button-1>', partial(self.records, (self.entry1.get(1.0, tk.END), self.entry2.get(1.0, tk.END))))

    def records(self, name, ip):
        self.db.insert_data(str(name), str(ip))
        self.view_records() 
                                                            
    def view_records(self):
        self.db.cur.execute('''SELECT * FROM tbl''')
        [self.tree.delete(i) for i in self.tree.get_children()]
        [self.tree.insert('', 'end', values=row) for row in self.db.cur.fetchall()]

    def delete_records(self):
        for selection_item in self.tree.selection():
            self.db.cur.execute('''DELETE FROM tbl WHERE id=?''', (self.tree.set(selection_item, '#1'),))
        self.db.conn.commit()
        self.view_records()    
        


class DB:
    def __init__(self):
        self.conn = sqlite3.connect('oop_test.db')
        self.cur = self.conn.cursor()
        self.cur.execute(
            '''CREATE TABLE IF NOT EXISTS tbl(id INTEGER PRIMARY KEY,name TEXT ,ip TEXT)''')
        self.conn.commit()

    def insert_data(self, name, ip):
        self.cur.execute('''INSERT INTO tbl(name, ip) VALUES (?, ?)''',(name,ip))
        self.conn.commit()

if __name__=='__main__':
    root=tk.Tk()
    db = DB()
    app = Main(root)
    app.pack()
    x = root.winfo_screenwidth()  
    y = root.winfo_screenheight()  
    root.geometry('{}x{}'.format(int(x*0.8), int(y*0.8)))  
    root['bg'] = '#2A3132'
    root.title('Main')
    root.state('zoomed')
    root.mainloop()


Я выделил нужную строку с кодом. Пытался получить данные из entry1 и entry2 в Child, и заносить их в БД с помощью имеющихся функций. Часть кода взял с youtube.
  • Вопрос задан
  • 73 просмотра
Решения вопроса 1
phaggi
@phaggi Куратор тега Python
лужу, паяю, ЭВМы починяю
Так вроде работает:
Код
import tkinter as tk
import sqlite3
from tkinter import ttk


class Main(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        self.db = db
        self.init_main()

    def init_main(self):
        lbl_main = tk.Label(text='TXT', fg='#336B87', font=('Modern', 220), bg='#2A3132')
        btn_database_workers = tk.Button(padx=7, pady=2, text='', bg='#336B87',
                                         activebackground='#336B87',
                                         compound=tk.TOP, font=('Ubuntu', 72), bd=10, command=self.open_database)
        lbl_main.pack()
        btn_database_workers.pack()

        lbl_main.place(x=5, y=-45)
        btn_database_workers.place(x=750, y=45)

    def open_database(self):
        Child()


class Child(tk.Toplevel):
    def __init__(self):
        super().__init__(root)
        self.init_child()
        self.db = db
        self.db.cur = self.db.conn.cursor()
        self.view = app
        self.view_records()

    def retrieve_input(self):
        entry1_text = self.entry1.get(1.0, tk.END)
        entry2_text = self.entry2.get(1.0, tk.END)
        self.records(entry1_text, entry2_text)

    def init_child(self):
        self.title('Child')
        self.geometry('950x400')
        self['bg'] = '#2A3132'
        self.resizable(False, False)

        self.entry1 = tk.Text(self, height=2, width=11, font=('Ubuntu', 15), bd=5)
        self.entry1.pack()
        self.entry1.place(x=3, y=180)

        self.entry2 = tk.Text(self, height=2, width=11, font=('Ubuntu', 15), bd=5)
        self.entry2.pack()
        self.entry2.place(x=3, y=245)

        self.tree = ttk.Treeview(self, column=('clm1', 'clm2', 'clm3'), show='headings')
        self.tree.heading('#1', text='ID')
        self.tree.heading('#2', text='Name')
        self.tree.heading('#3', text='IP')
        self.tree.pack()

        delete_btn = tk.Button(self, text='Delete', padx=25, pady=10, font=('Ubuntu', 15),
                               bd=8, bg='#336B87', command=self.delete_records)
        delete_btn.pack()
        delete_btn.place(x=0, y=0)

        add_btn = tk.Button(self, text='Add', padx=36, pady=10, font=('Ubuntu', 15), bd=8, bg='#336B87',
                            command=lambda: self.retrieve_input())
        add_btn.pack()
        add_btn.place(x=0, y=75)

    def records(self, name, ip):
        self.db.insert_data(str(name), str(ip))
        self.view_records()

    def view_records(self):
        self.db.cur.execute('''SELECT * FROM tbl''')
        [self.tree.delete(i) for i in self.tree.get_children()]
        [self.tree.insert('', 'end', values=row) for row in self.db.cur.fetchall()]

    def delete_records(self):
        for selection_item in self.tree.selection():
            self.db.cur.execute('''DELETE FROM tbl WHERE id=?''', (self.tree.set(selection_item, '#1'),))
        self.db.conn.commit()
        self.view_records()


class DB:
    def __init__(self):
        self.conn = sqlite3.connect('oop_test.db')
        self.cur = self.conn.cursor()
        self.cur.execute(
            '''CREATE TABLE IF NOT EXISTS tbl(id INTEGER PRIMARY KEY,name TEXT ,ip TEXT)''')
        self.conn.commit()

    def insert_data(self, name, ip):
        self.cur.execute('''INSERT INTO tbl(name, ip) VALUES (?, ?)''', (name, ip))
        self.conn.commit()


if __name__ == '__main__':
    root = tk.Tk()
    db = DB()
    app = Main(root)
    app.pack()
    x = root.winfo_screenwidth()
    y = root.winfo_screenheight()
    root.geometry('{}x{}'.format(int(x * 0.8), int(y * 0.8)))
    root['bg'] = '#2A3132'
    root.title('Main')
    root.state('zoomed')
    root.mainloop()
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы