from tkinter import Tk, Text, END, INSERT, Label, CURRENT
class Application(Tk):
def __init__(self):
super().__init__()
self.widget_text = Text(self)
self.widget_text.pack(expand=True)
self.configure_key_words()
self.widget_text.bind("<KeyPress>", self.handler)
def get_last_line(self):
full_text = self.widget_text.get("1.0", END)
list_string = full_text.split('\n')[::-1]
last_line = list_string[1]
return last_line
def get_last_word(self):
last_word = self.get_last_line().split(' ')[-1]
return last_word
def configure_key_words(self):
self.widget_text.tag_config('apple', foreground='red', underline=1,
font=("Arial", 12, 'bold'))
self.widget_text.tag_config('banana', foreground='green',
font=("Arial", 12, 'bold'))
def handler(self, event):
last_word = self.get_last_word()
if event.char == ' ' or '\n':
line, _ = self.widget_text.index(CURRENT).split(".")
word_start_position = self.get_last_line().rfind(last_word)
match last_word:
case "яблоко":
print(line, word_start_position)
self.widget_text.delete(f"{line}.{word_start_position}", END)
self.widget_text.insert(f"{line}.{word_start_position}", 'яблоко', 'apple')
case "банан":
print(line, word_start_position)
self.widget_text.delete(f"{line}.{word_start_position}", END)
self.widget_text.insert(f"{line}.{word_start_position}", 'банан', 'banana')
def main():
Application().mainloop()
if __name__ == '__main__':
main()
from datetime import datetime
from tkinter import *
from functools import partial
root = Tk()
root.title("Запись давления")
root.geometry('300x200+200+200')
pressure = StringVar()
pulse = StringVar()
datetime = datetime.now()
lbl1 = Label(root,text="Давление")
ent1 = Entry(textvariable=pressure, font=17)
lbl2 = Label(root,text="Пульс")
ent2 = Entry(textvariable=pulse, font=17)
lbl1.pack()
ent1.pack()
lbl2.pack()
ent2.pack()
def write(pulse, pressure, datetime):
with open("pulse.txt", "w") as file:
data = "Время: {0}\nПульс: {1}\nДавление: {2}".format(datetime, pulse.get(), pressure.get())
file.write(data)
butt = Button(root,text="Записать", command=partial(write, pressure, pulse, datetime))
butt.pack()
root.mainloop()
from tkinter import Tk, Button, mainloop
from vlc import MediaPlayer
URL = "https://str2.pcradio.ru/Eminem-med"
class Player(Tk):
def __init__(self):
print("Инициализация Player")
self.player = MediaPlayer()
super().__init__()
self.button = Button(self, text="Воспроизвести файл из интернета")
self.button.configure(command=self.play)
self.button.pack()
self.protocol("WM_DELETE_WINDOW", self.on_closing)
def play(self):
return self.player.play()
def set_mrl(self, mrl):
return self.player.set_mrl(mrl)
def on_closing(self):
self.player.stop()
del self.player
self.destroy()
class TkPlayer(Player):
pass
def main():
tk_player = TkPlayer()
tk_player.set_mrl(URL)
tk_player.mainloop()
if __name__ == '__main__':
main()
from tkinter import Tk, Entry, Checkbutton, mainloop
class Example(Tk):
def __init__(self):
super().__init__()
self.input_field_1 = Entry(self)
self.input_field_1.grid(row=0, column=0)
self.check_button_1 = Checkbutton(self)
self.check_button_1.grid(row=0, column=1)
self.input_field_2 = Entry(self)
self.input_field_2.grid(row=1, column=0)
self.check_button_2 = Checkbutton(self, command=self.disable_or_normal_input_field_2)
self.check_button_2.grid(row=1, column=1)
def disable_or_normal_input_field_2(self):
if self.input_field_2['state'] == 'normal':
self.input_field_2.configure(state="disable")
else:
self.input_field_2.configure(state="normal")
print("Поле ввода 2 статус:", self.input_field_2['state'])
def main():
example = Example()
example.mainloop()
if __name__ == '__main__':
main()
from tkinter import Tk, Button, Label, LabelFrame, mainloop
from functools import partial
SIGNAL = int
class App(Tk):
normal_engine_speed = 1500
def __init__(self):
super().__init__()
self.interface()
def interface(self):
self.title("Управление станком")
self["bg"] = "gray22"
self.geometry("300x150+500+300")
self.resizable(False, False)
title_label = Label(self, text="Обороты двигателя")
title_label.config(font="Times 18 bold", fg="green")
title_label.place(x=40)
button_reduce_speed = Button(self, text="-10")
button_reduce_speed.config(font="Times 13 bold", fg="blue")
button_reduce_speed.bind('<Button-1>', partial(self.button_click_handler, 0))
button_reduce_speed.place(x=0, y=0)
button_add_speed = Button(self, text="+10")
button_add_speed.config(font="Times 13 bold", fg="blue")
button_add_speed.bind('<Button-1>', partial(self.button_click_handler, 1))
button_add_speed.place(x=261, y=0)
self.show_engine_speed = Label(self, text=self.normal_engine_speed)
self.show_engine_speed.config(font="Times 30 bold", bg="black", fg="green")
self.show_engine_speed.config(width=13, height=2)
self.show_engine_speed.place(y=40)
def button_click_handler(self, SIGNAL, event):
if SIGNAL == 0:
self.normal_engine_speed -= 10
elif SIGNAL == 1:
self.normal_engine_speed += 10
self.show_engine_speed["text"] = self.normal_engine_speed
if __name__ == "__main__":
app = App()
app.mainloop()
from random import randint
from tkinter import Tk, Label, mainloop
from time import sleep
class App(Tk):
def __init__(self):
super().__init__()
self.label = Label(self)
self.label.pack()
self.run()
def run(self):
self.label["text"] = str(randint(1, 10000))
self.after(1000, self.run)
app = App()
app.mainloop()
import os
import tkinter as tk
from tkinter import *
#for name in os.listdir("C://"):
# print (name)
class Main(tk.Frame):
def __init__(self, root):
super().__init__(root)
self.toolbar()
self.Text()
def toolbar(self): # Добавляю в тулбар кнопки
toolbar = tk.Frame(bg='#d7d8e0', bd=4) # Создаём тулбар
toolbar.pack(side=tk.TOP, fill=tk.X)
btn_new = tk.Button(toolbar, text='Создать файл', bd = 4)
btn_new.pack(side=tk.LEFT)
btn_save = tk.Button(toolbar, text='Сохранить файл', bd = 4, command=self.saveTextField)# Вот здесь вы вызываете функцию но не передаёте параметры saveTextField(self, textField << Вот) да и по моему пр таком вызове и нельзя передать параметры
btn_save.pack(side=tk.LEFT)
def saveTextField(self):
with open("example.txt", "w") as file:
file.write(self.textField.get(1.0, END))
def Text(self):
self.textField = Text(width=200, height=100, fg='black', wrap=WORD) # что сделать object доступным во всём классе используйте self я вот это self.textField использую в это функции saveTextField
self.textField.pack()
if __name__ == "__main__": # Если окно запущенно, то создает наше главное окно
root = tk.Tk()
app = Main(root)
app.pack()
root.title("Text 0.01v")
root.geometry("800x600+450+100")
root.resizable(True, True)
root.mainloop()