Top.Mail.Ru
Ответы
Аватар пользователя
2 года назад
от
Изменено

Задача: Добавить внизу текстового редактора количество введённых символов ПОМОГИТЕ ПОЖАЛУЙСТА!!! питон

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
 import tkinter as tk 
from tkinter.messagebox import *# импорт месседжбоксов 
from tkinter import filedialog# диалоговые окна 
from tkinter import * 
root=tk.Tk() 
root.title("Блокнот") 
root.geometry("600x600+300+200") 
root.minsize(200,100) 
root.maxsize(1920,1080) 
main_menu=tk.Menu(root) 
root.config(menu=main_menu) 
about_open=False 
def save_file(): 
    file_name=filedialog.asksaveasfilename(initialdir='/', 
                                   title='Сохранить как', 
                                   filetypes=(('Текстовые файлы','*.txt'),('Все файлы','*.*'))) 
    if file_name: 
        with open(file_name+'.txt','w')as f: 
            text_save= str(text.get(1.0,tk.END)) 
            f.write(text_save) 
def new_file(): 
    text_save=str(text.get(1.0,tk.END)) 
    if text_save!='\n': 
         
    #print(f'>{text_save}<')#проверка 
   # text.delete('1.0',tk.END)#Удалить с 1 символа до конца 
    #showinfo(title='Текст1',message='текст2')# showinfo,showwarning отличие в том что просто разные значки выводит окно  которое останавливает программу до тех пор пока мы не взаимодействуем с ним выводит Ок 
    #askyesno(title='Текст1',message='текст2')# 2 вид окон который выводит да нет 
    #askokcancel(title='Текст1',message='текст2') выводитОкей отмена 
    #askretrycancel(title='Текст1',message='текст2')#Повтор отмена 
        answer=askyesnocancel(title='Сохранить файл',message='Сохранить изменения?')# 3 кномки да нет отмена ВСЕ ФУНКЦИИ НАЧИНАЮЩИЕСЯ НА ask  ВОЗВРАЩАЮТ РЕЗУЛЬТАТ TRue false None 
        if answer: 
            save_file() 
        elif answer==False: 
            text.delete('1.0',tk.END) 
        else: 
            return False 
    return True 
def open_file(): 
    if new_file(): 
        file_name=filedialog.askopenfilename(initialdir='/', 
                                   title='Открыть файл', 
                                   filetypes=(('Текстовые файлы','*.txt'),('Все файлы','*.*')))# Спросить какой файл открыть   initialdir='/' деректория по умолчанию/ filetypes=(('Текстовые файлы','*.txt'),('Все файлы','*.*')))указываем какие именно файлы 
        if file_name: 
            with open (file_name,'r')as f:# окрыли файл в блакноте 
                text_open=f.read() 
                 
                text.insert(1.0,text_open) 
def exit_func(): 
    root.destroy() 
def about(): 
    global about_open 
    if about_open==False: 
        root_help=tk.Tk() 
        root_help.geometry("300x70+300+450") 
        root_help.resizable(False,False) 
        root_help.title("О программе") 
        about_open=True 
        def help_exit(): 
            global about_open 
            about_open=False 
            root_help.destroy() 
        help_label=tk.Label(root_help,text="Создатель: студент группы П-24 _____________") 
        help_label.pack() 
        help_button=tk.Button(root_help,text="Закрыть",command=help_exit) 
        help_button.pack() 
file_menu=tk.Menu(main_menu,tearoff=0) 
file_menu.add_command(label="Новый файл",command=new_file) 
file_menu.add_command(label="Открыть файл",command=open_file) 
file_menu.add_command(label="Сохранить как",command=save_file) 
file_menu.add_command(label="Выход",command=exit_func) 
main_menu.add_cascade(label="Файл",menu=file_menu) 
 
help_menu=tk.Menu(main_menu,tearoff=0) 
help_menu.add_command(label="Помощь") 
help_menu.add_command(label="О программе",command=about) 
main_menu.add_cascade(label="Помощь",menu=help_menu) 
 
 
text=tk.Text(root,width=30)#отобразили текст на экране 
text.pack(fill=tk.BOTH,expand=tk.YES,side=tk.LEFT) 
scroll=tk.Scrollbar(command=text.yview) 
scroll.pack(side=tk.LEFT,fill=tk.Y) 
text.config(yscrollcommand=scroll.set) 

 
 
 
root.mainloop() 
 
Только авторизированные пользователи могут оставлять свои ответы
Дата
Популярность
Аватар пользователя
Знаток

try it
измененный код:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
 import tkinter as tk 
from tkinter.messagebox import * 
from tkinter import filedialog 
from tkinter import * 
 
root = tk.Tk() 
root.title("Блокнот") 
root.geometry("600x600+300+200") 
root.minsize(200, 100) 
root.maxsize(1920, 1080) 
 
main_menu = tk.Menu(root) 
root.config(menu=main_menu) 
 
about_open = False 
 
def save_file(): 
    file_name = filedialog.asksaveasfilename(initialdir='/', title='Сохранить как', 
                                            filetypes=(('Текстовые файлы', '*.txt'), ('Все файлы', '*.*'))) 
    if file_name: 
        with open(file_name + '.txt', 'w') as f: 
            text_save = str(text.get(1.0, tk.END)) 
            f.write(text_save) 
 
def new_file(): 
    text_save = str(text.get(1.0, tk.END)) 
    if text_save != '\n': 
        answer = askyesnocancel(title='Сохранить файл', message='Сохранить изменения?') 
        if answer: 
            save_file() 
        elif answer == False: 
            text.delete('1.0', tk.END) 
        else: 
            return False 
    return True 
 
def open_file(): 
    if new_file(): 
        file_name = filedialog.askopenfilename(initialdir='/', title='Открыть файл', 
                                               filetypes=(('Текстовые файлы', '*.txt'), ('Все файлы', '*.*'))) 
        if file_name: 
            with open(file_name, 'r') as f: 
                text_open = f.read() 
                text.insert(1.0, text_open) 
 
def exit_func(): 
    root.destroy() 
 
def about(): 
    global about_open 
    if about_open == False: 
        root_help = tk.Tk() 
        root_help.geometry("300x70+300+450") 
        root_help.resizable(False, False) 
        root_help.title("О программе") 
        about_open = True 
 
        def help_exit(): 
            global about_open 
            about_open = False 
            root_help.destroy() 
 
        help_label = tk.Label(root_help, text="Создатель: студент группы П-24 _____________") 
        help_label.pack() 
        help_button = tk.Button(root_help, text="Закрыть", command=help_exit) 
        help_button.pack() 
 
file_menu = tk.Menu(main_menu, tearoff=0) 
file_menu.add_command(label="Новый файл", command=new_file) 
file_menu.add_command(label="Открыть файл", command=open_file) 
file_menu.add_command(label="Сохранить как", command=save_file) 
file_menu.add_command(label="Выход", command=exit_func) 
main_menu.add_cascade(label="Файл", menu=file_menu) 
 
help_menu = tk.Menu(main_menu, tearoff=0) 
help_menu.add_command(label="Помощь") 
help_menu.add_command(label="О программе", command=about) 
main_menu.add_cascade(label="Помощь", menu=help_menu) 
 
text = tk.Text(root, width=30) 
text.pack(fill=tk.BOTH, expand=tk.YES, side=tk.LEFT) 
scroll = tk.Scrollbar(command=text.yview) 
scroll.pack(side=tk.LEFT, fill=tk.Y) 
text.config(yscrollcommand=scroll.set) 
 
# Создание метки для отображения количества символов 
char_count_label = tk.Label(root) 
char_count_label.pack(side=tk.BOTTOM) 
 
def update_char_count(event): 
    char_count = len(text.get(1.0, tk.END)) - 1  # Вычитаем символ новой строки 
    char_count_label.config(text=f"Количество символов: {char_count}") 
 
# Привязка события ввода текста к обновлению количества символов 
text.bind("<KeyRelease>", update_char_count) 
 
root.mainloop()