A
A
Artyom D2021-09-07 09:56:19
Python
Artyom D, 2021-09-07 09:56:19

How to clear an input field in Tkinter?

Hello, I need help. I'm learning Python and decided to write a small program to understand things a bit.

The idea is that the program should perform three functions:

  1. Receive data from the user and enter it into a file.
  2. When prompted by the user, read the file and display the data in a tabular form.
  3. Delete unnecessary data (error or loss of relevance).


Initially I tried to write a purely console script, now I want to add some "pretty things". I use Tkinter for this.

At this stage, a function is ready to receive data and write to a file. There is also a function of reading and output in a tabular form (only in the console, until I figured out how to display them in the program window). Now this is all ready-made functionality.

The problem is this: the user enters data, presses the button, everything is recorded perfectly and a notification pops up, then you need to clear the fields and wait for the next user action.

I read about how you can clear the input field, tried several options, but not one worked. Who can tell how to fix this?

If there are any comments on the code, write in the comments.

from tkinter import *
from tkinter import messagebox
import pandas as pd
import os



def clear ():
    NameUserEntry.delete("0", END)
    NumbersEntry.delete("0", END)
    CarEntry.delete("0", END)
    VolumeSEntry.delete("0", END)
    PriceSEntry.delete("0", END)
    VolumeFEntry.delete("0", END)
    PriceFEntry.delete("0", END)
    ExpensesEntry.delete("0", END)



def data_user():
    os.system('CLS')
    print("Получение данных....", end="")
    name_driver = NameUserEntry.get()
    number_driver = NumbersEntry.get()
    car_driver = CarEntry.get()
    volume_start = int(VolumeSEntry.get())
    price_start = int(PriceSEntry.get())
    volume_finish = int(VolumeFEntry.get())
    price_finish = int(PriceFEntry.get())
    expenses = int(ExpensesEntry.get())
    profit = volume_finish * price_finish - volume_start * price_start - expenses
    print('Ок')
    os.system('CLS')
    
    print("Формируется словарь....", end="")
    data_driver = {
        'name':name_driver,
        'numbers':number_driver,
        'car':car_driver,
        'Vs':volume_start,
        'Ps':price_start,
        'Vf':volume_finish,
        'Pf':price_finish,
        'Ex':expenses,
        'Prof':profit,
        }
    print("Ок")


    
    print("Собираем фрейм...", end="")
    columns = ['ФИО', 'Телефон', 'Машина', 'Объем на старте', 'Цена покупки',
               'Объем на выходе', 'Цена продажи', 'Затраты', 'Профит',]

    data = 
    
    df = pd.DataFrame(data, columns=columns)
    print('Ок')
    
    print('Делаем запись....', end='')
    df.to_csv(r'data.csv', mode='a', sep='/', 
        header=False, index=False, encoding='utf-8')
    print('Ок')
    positive = 'Запись успешно добалена!'
    messagebox.showinfo('Уведомление', positive)
    

    
def read_data():
    df =pd.read_csv(r'data.csv', sep='/', names = ['ФИО', 
        'Телефон', 'Машина', 'Объем на старте', 'Цена покупки',
        'Объем на выходе', 'Цена продажи', 'Затраты', 'Профит'])
    print(df)


root = Tk()
root.title('F1')
root.geometry('500x600')

button_padding = {'ipadx':5, 'ipady':5}
header_padding = {'padx':10, 'pady':12}
#ФИО водителя
NameUserLabel = Label(root, text='ФИО водителя: ', **header_padding)
NameUserLabel.grid(row = 1, rowspan=1, column=1, sticky='w')

NameUserEntry = Entry(root, bg='#fff', fg='#444')
NameUserEntry.grid(row = 2, rowspan=1, column=1,sticky='w')


#Номер телефона
NumbersLabel = Label(root, text='Номер телефона: ')
NumbersLabel.grid(row = 1, rowspan=1, column=3, sticky='w')

NumbersEntry = Entry(root, bg='#fff', fg='#444')
NumbersEntry.grid(row = 2, rowspan=1, column=3,sticky='w')


#марка машины, номер
CarLabel = Label(root, text='Машина(марка,г.с.з.: ', **header_padding)
CarLabel.grid(row = 3, rowspan=1, column=1, sticky='w')

CarEntry = Entry(root, bg='#fff', fg='#444')
CarEntry.grid(row = 4, rowspan=1, column=1,sticky='w')


#объем при покупке
VolumeSLabel = Label(root, text='Объем (покупка): ', **header_padding)
VolumeSLabel.grid(row = 6, rowspan=1, column=1, sticky='w')

VolumeSEntry = Entry(root, bg='#fff', fg='#444')
VolumeSEntry.grid(row = 7, rowspan=1, column=1,sticky='w')


#цена покупки
PriceSLabel = Label(root, text='Цена (покупка): ')
PriceSLabel.grid(row = 6, rowspan=1, column=3, sticky='w')

PriceSEntry = Entry(root, bg='#fff', fg='#444')
PriceSEntry.grid(row = 7, rowspan=1, column=3,sticky='w')



#объем при продаже
VolumeFLabel = Label(root, text='Объем (продажа): ', **header_padding)
VolumeFLabel.grid(row = 9, rowspan=1, column=1, sticky='w')

VolumeFEntry = Entry(root, bg='#fff', fg='#444')
VolumeFEntry.grid(row = 10, rowspan=1, column=1,sticky='w')



#цена при продаже
PriceFLabel = Label(root, text='Цена (продажа): ')
PriceFLabel.grid(row = 9, rowspan=1, column=3, sticky='w',)

PriceFEntry = Entry(root, bg='#fff', fg='#444')
PriceFEntry.grid(row = 10, rowspan=1, column=3,sticky='w')

#прочие затраты
ExpensesLabel = Label(root, text='Прочие затраты: ', **header_padding)
ExpensesLabel.grid(row = 12, rowspan=1, column=1, sticky='w')

ExpensesEntry = Entry(root, bg='#fff', fg='#444', )
ExpensesEntry.grid(row = 13, rowspan=1, column=1,sticky='w')

#профит, высчитывается и вносится в таблицу

# кнопка сделать запись
ButtonWrite = Button(root, text='Сделать запись', bg='#fff', fg='#444')
ButtonWrite.grid(row = 15, rowspan=1, column=1, sticky='ws')
ButtonWrite.config(command=data_user)

# кнопка очистки данных
ButtonDelete = Button(root, text='очистить данные', bg='#fff', fg='#444')
ButtonDelete.grid(row = 15, rowspan=1, column=3, sticky='w')
ButtonDelete.config(command=clear)

root.mainloop()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-09-07
@Vindicar

You can delete part of the text from the entry field (Entry) using the delete () method.
entry.delete(0, tk.END)
And insert using the insert()
method entry.insert(0, 'string')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question