Создадим в Linux Rosa Fresh R13 (R12) окно с кнопками на Python, добавим кнопки, картинки, кнопку сброса (reset) и сдвинем окно приложения от центра и запустим одновременно редактор кода, окно приложения и другое.
Полный код приложения на Python tkinter смотрите в конце статьи.
Само приложение:
Код приложения – управляет микросхемой (atmega,pic) через ПК на Python через UART.
Расположение элементов в окне приложения через grid (сетку – строчки и столбцы – чтобы разместить несколько полей ввода горизонтально).
——————————
Кнопка сброса (reset):
——————————–
Создаём кнопку и прописываем при клике на неё выполнить команду komanda6
# Create a button reset button6 = tk.Button(root, text="Перезапустить", command=komanda6) button6.grid(row=6,column=0)
Прописываем команду komanda6:
def komanda6():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
python = sys.executable
os.execl(python, python, * sys.argv)
И не забываем указать в начале файла python следующий код:
import sys import os
———————–
Сдвинем окно приложения от центра
————————————–
Вот эта строчка отвечает за размер окна (300х500 – ширина и высота), а (+700 и +40 – сдвиг окна с относительно левого верхнего угла монитора на 700 вправо и 40 вниз)
root.geometry('300x500+700+40')
Если не хотите двигать приложение от центра, то просто укажите его ширину и длину:
root.geometry('300x500')
—————————————————–
Запускаем без консоли (терминала) – для этого создадим sh файл:
—————————————————–
Создаем в редакторе кода – блокноте (KWrite) файл, и сохраняем его, например как 1.sh
Открываем терминал (Ctrl+Alt+T).
Переходим в папку с файлом sh (в нашем примере 1.sh) – для этого воспользуйтесь командами cd и dir (или просто правой кнопкой мыши – “Открыть терминал в этой папке”).
Далее запускаем в терминале Linux Rosa Fresh следующую команду, которая делает sh файл исполняемым:
chmod +x 1.sh
Далее в редакторе кода – блокноте (KWrite) пишем следующий код:
#!/bin/bash python3 100.py
Можно довить ещё вывод редактора кода (у меня KWrite):
#!/bin/bash python3 100.py & kwrite 100.py &
И так как у нас уже имеется кнопка “Перезагрузить”, то можно менять код приложения, а далее нажимать кнопку “Перезагрузить”, чтобы изменения вступили в силу.
Также при запуске редактора кода можно его удобно позиционировать, и при запуске у вас будет получать вроде этого:
Всё готово! Теперь можно управлять без консоли!
———————————————
———————————————
Полный код приложения на Python tkinter
——————————————-
import tk
import tkinter as tk
import serial
import time
# Добавляем изображение
from tkinter import *
import sys
import os
# Configure the COM port
port = "/dev/ttyUSB0" # Replace with the appropriate COM port name
baudrate = 9600
#----------------------------------------------------------------
def komanda1():
print("1")
try:
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
command = "1"
ser.write(command.encode())
time.sleep(1)
command = "2"
ser.write(command.encode())
command = "5"
ser.write(command.encode())
time.sleep(1)
command = "6"
ser.write(command.encode())
command = "7"
ser.write(command.encode())
time.sleep(1)
command = "8"
ser.write(command.encode())
command = "9"
ser.write(command.encode())
time.sleep(1)
command = "a"
ser.write(command.encode())
command = "b"
ser.write(command.encode())
time.sleep(1)
command = "c"
ser.write(command.encode())
command = "f"
ser.write(command.encode())
time.sleep(1)
command = "g"
ser.write(command.encode())
command = "j"
ser.write(command.encode())
time.sleep(1)
command = "k"
ser.write(command.encode())
command = "l"
ser.write(command.encode())
time.sleep(1)
command = "m"
ser.write(command.encode())
command = "n"
ser.write(command.encode())
time.sleep(1)
command = "o"
ser.write(command.encode())
command = "p"
ser.write(command.encode())
time.sleep(1)
command = "q"
ser.write(command.encode())
command = "r"
ser.write(command.encode())
time.sleep(1)
command = "s"
ser.write(command.encode())
command = "t"
ser.write(command.encode())
time.sleep(1)
command = "u"
ser.write(command.encode())
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda2():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
command = "5"
ser.write(command.encode())
command = "7"
ser.write(command.encode())
time.sleep(0.5)
command = "9"
ser.write(command.encode())
command = "2"
ser.write(command.encode())
time.sleep(0.5)
command = "b"
ser.write(command.encode())
command = "6"
ser.write(command.encode())
time.sleep(0.5)
command = "f"
ser.write(command.encode())
command = "8"
ser.write(command.encode())
time.sleep(0.5)
command = "j"
ser.write(command.encode())
command = "a"
ser.write(command.encode())
time.sleep(0.5)
command = "l"
ser.write(command.encode())
command = "c"
ser.write(command.encode())
time.sleep(0.5)
command = "n"
ser.write(command.encode())
command = "g"
ser.write(command.encode())
time.sleep(0.5)
command = "p"
ser.write(command.encode())
command = "k"
ser.write(command.encode())
time.sleep(0.5)
command = "r"
ser.write(command.encode())
command = "m"
ser.write(command.encode())
time.sleep(0.5)
command = "t"
ser.write(command.encode())
command = "o"
ser.write(command.encode())
time.sleep(0.5)
command = "q"
ser.write(command.encode())
time.sleep(0.5)
command = "s"
ser.write(command.encode())
time.sleep(0.5)
command = "u"
ser.write(command.encode())
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda3():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "3"
ser.write(command.encode())
command = "1"
ser.write(command.encode())
time.sleep(0.5)
command = "5"
ser.write(command.encode())
command = "2"
ser.write(command.encode())
time.sleep(0.5)
command = "7"
ser.write(command.encode())
command = "6"
ser.write(command.encode())
time.sleep(0.5)
command = "9"
ser.write(command.encode())
command = "8"
ser.write(command.encode())
time.sleep(0.5)
command = "d"
ser.write(command.encode())
command = "f"
ser.write(command.encode())
command = "a"
ser.write(command.encode())
time.sleep(0.5)
command = "h"
ser.write(command.encode())
command = "l"
ser.write(command.encode())
command = "e"
ser.write(command.encode())
command = "g"
ser.write(command.encode())
time.sleep(0.5)
command = "v"
ser.write(command.encode())
command = "p"
ser.write(command.encode())
command = "i"
ser.write(command.encode())
command = "m"
ser.write(command.encode())
time.sleep(0.5)
command = "t"
ser.write(command.encode())
command = "w"
ser.write(command.encode())
command = "q"
ser.write(command.encode())
time.sleep(0.5)
command = "u"
ser.write(command.encode())
time.sleep(0.5)
command = "4"
ser.write(command.encode())
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda4():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "2"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
#----------------------------------------------------------------
def komanda5():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
print("Entered Text:", entry1.get())
command = entry1.get()
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = entry2.get()
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda6():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
python = sys.executable
os.execl(python, python, * sys.argv)
#----------------------------------------------------------------
# Кнопки
def greet(name):
print(f"Привет, {name}!")
root = tk.Tk()
root.title("Пример окна с кнопками")
#w = root.winfo.screenwidth()
#w = w-100
#root.geometry("300x500")
root.geometry('300x500+700+40')
#root.geometry(f'300x500+{w}')
button1 = tk.Button(root, text="Команда 1", bg="blue", fg="white", font=("Arial", 14), command=komanda1)
button1.grid(row=0,column=0)
button2 = tk.Button(root, text="Команда 21", bg="red", fg="black", font=("Helvetica", 12), command=komanda2)
button2.grid(row=1,column=0)
button3 = tk.Button(root, text="Запуск команды 3", command=komanda3)
button3.grid(row=2,column=0)
button4 = tk.Button(root, text='Запуск команды 4', command=komanda4)
button4.grid(row=3,column=0)
# Create an Entry widget
entry1 = tk.Entry(root, width=2)
entry1.grid(row=4,column=0)
# Create an Entry widget
entry2 = tk.Entry(root, width=2)
entry2.grid(row=4,column=1)
# Create a button to retrieve text
button5 = tk.Button(root, text="Выполнить", command=komanda5)
button5.grid(row=5,column=0)
# Create a button reset
button6 = tk.Button(root, text="Перезапустить", command=komanda6)
button6.grid(row=6,column=0)
# Добавляем изображение
img1 = PhotoImage(file='p1.png')
Label(image=img1, bg='lightyellow',text='Изображение',compound=TOP).grid(row=7,column=0)
root.mainloop()
————————————–
Как установить
————————————-
Сначала вводим команду и проверяем установлен ли pip (позволяет устанавливать сторонние библиотеки на Python). Обычно pip уже установлен вместе с Python. Проверить наличие и версию pip можно командой – введя её в Терминале (Консоли, вызвать можно Ctrl+Alt+T):
sudo urpmi python3-pip
У меня на Linux Rosa Fresh 13 Plasma уже был установлен python3-pip-24.2-1.noarch.
А далее устанавливаем библиотеку pyserial с помощью команды:
sudo python3-pip install pyserial




