我想CheckButton
使用 function获取小部件的状态gtk_check_button_get_active()
,但找不到这样的功能。对于其他小部件,存在类似的功能并且可以正常工作。
Булат's questions
组装时,会出现一条消息,说它看不到gtk/gtk.h
. 如果你指出这一点gtk-3.0/gtk/gtk.h
并且gtk-3.0/gdk/gdk.h
已经对别的东西发誓。但最重要的是,如果你尝试通过控制台编译这段代码:
#include <gtk/gtk.h>
static void
activate (GtkApplication* app,
gpointer user_data)
{
GtkWidget *window;
window = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (window), "Window");
gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);
gtk_widget_show_all (window);
}
int
main (int argc,
char **argv)
{
GtkApplication *app;
int status;
app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
status = g_application_run (G_APPLICATION (app), argc, argv);
g_object_unref (app);
return status;
}
使用以下命令一切都会好起来的:
gcc `pkg-config --cflags gtk+-3.0` -o test test.c `pkg-config --libs gtk+-3.0`
在 Ubuntu 22.04 上工作
附言
Cmake 输出:
/snap/clion/198/bin/cmake/linux/bin/cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_MAKE_PROGRAM=/snap/clion/198/bin/ninja/linux/ninja -G Ninja -S /home/home-pc/CLionProjects/gtk_PNX -B /home/home-pc/CLionProjects/gtk_PNX/cmake-build-debug
-- Configuring done
-- Generating done
-- Build files have been written to: /home/home-pc/CLionProjects/gtk_PNX/cmake-build-debug
[Finished]
CMakeLists.txt:
cmake_minimum_required(VERSION 3.22)
project(gtk_PNX C)
set(CMAKE_C_STANDARD 99)
add_executable(gtk_PNX main.c)
我创建 self.work_timer = threading.Timer(0.5, self.blue_connect)
了一个计时器,它在按下按钮时启动,并在self.blue_connect
代码内部无限循环。进一步覆盖closeEvent
def closeEvent(self, event):
self.work_function.cancel()
event.accept()
我在其中写了关闭计时器,但是,在 GUI 结束后,脚本仍然在后台运行
有一段代码将未启动的沙箱标记为红色。该函数start_btn()
检查 CheckButtons,然后启动标记的按钮,标签立即着色为绿色。问题是什么 - 如何确保
self.builder.get_object(f"status_label_{box}").set_markup("бла бла бла")
在重新调用start_box()
循环启动框的函数之前,在该行之后有 N 秒的超时,但是这个超时不应该阻塞 GUI,也就是说,它会time.sleep()
飞走立即地
import gi
import os
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GLib
sandboxie_path = "C:/Program Files/Sandboxie-Plus/Start.exe" # Путь к Start.exe
Steam_path = "C:/Program Files (x86)/Steam/steam.exe" # Путь к steam.exe
tn_host = "127.0.0.1"
port_list = ["2121", "2122", "2123", "2124", "2125", "2126"]
server_list = ["85.88.162.140:27031"]
check_list = []
def start_box(box_num, tn_port, server, sandbox_path, steam_path):
os.popen(f'"{sandbox_path}" /box:{box_num} "{steam_path}" -applaunch 730 -netconport {tn_port} -novid '
f'-window -nosound +fps_max 30 -w 640 -h 480 +left connect {server}')
class Main:
def __init__(self):
gladeFile = "res/csgo.glade"
self.builder = Gtk.Builder()
self.builder.add_from_file(gladeFile)
self.builder.connect_signals(self)
window = self.builder.get_object("main")
window.connect('delete-event', Gtk.main_quit)
window.show()
def red_mark(self):
for num in range(1, 7):
self.builder.get_object(f"status_label_{num}").set_markup("<span background='#FA6DA4' "
"foreground='#000000'>OFF</span>")
def start_btn(self, widget):
for box in range(1, 7):
if self.builder.get_object(f"check_btn_{box}").get_active():
start_box(box, port_list[box - 1], server_list[0], sandboxie_path, Steam_path)
self.builder.get_object(f"status_label_{box}").set_markup("<span background='#76EE98' "
"foreground='#000000'>ON</span>")
# Тайм-аут на N секунд
if __name__ == '__main__':
main = Main()
main.red_mark()
Gtk.main()
本质
第一个脚本启动,搜索可用的串行端口并将它们添加到列表中,将它们传递给另一个脚本,然后重新加载(无法强制serial.tools.list_ports在循环中查找端口)。第二个脚本接受一个列表并且已经将它用于某些目的。问题是如何实现脚本之间的通信,前提是其中一个不断重新加载。如果可以不重新加载第一个脚本,而是循环查找端口,那就更好了
这是一个示例代码:
import serial.tools.list_ports
port_list = []
def search_ports():
ports = serial.tools.list_ports.comports()
for port, desc, hwid in sorted(ports):
port_list.append(port)
search_ports()
该程序需要每 5 分钟备份一次游戏存档。我取日期和时间,将其写入 x变量,然后写入名称。我创建了一个模板文件夹并将 3 个保存文件复制到其中,然后将文件夹重命名为name并休息 5 分钟
但!
如果你循环执行函数,第一轮顺利,第二轮出现问题 - 模板文件夹仍然创建,但没有重命名。并且已经在第 3 圈发生错误,说savprot文件夹已经存在
如果您重新启动脚本并且不循环它,则不会出现错误。但我不知道该怎么做
import os
import time
from datetime import datetime
import shutil
x = datetime.now()
def backup():
name = '{}.{}.{} _ {}.{}.{}'.format(x.day, x.month, x.year, x.hour,
x.minute, x.second)
os.mkdir('C:\\WGsav\\savprot')
shutil.copy2('C:\\ProgramData\\Orbit\\274\\RLD!\\Save001.sav', 'C:\\WGsav\\savprot')
shutil.copy2('C:\\ProgramData\\Orbit\\274\\RLD!\\Save002.sav', 'C:\\WGsav\\savprot')
shutil.copy2('C:\\ProgramData\\Orbit\\274\\RLD!\\saves.ini', 'C:\\WGsav\\savprot')
os.rename('C:\\WGsav\\savprot', 'C:\\WGsav\\{}'.format(name))
time.sleep(300)
backup()
有循环:
import os
import time
from datetime import datetime
import shutil
import subprocess
x = datetime.now()
while 1:
name = '{}.{}.{} _ {}.{}.{}'.format(x.day, x.month, x.year, x.hour,
x.minute, x.second)
os.mkdir('C:\\WGsav\\savprot')
shutil.copy2('C:\\ProgramData\\Orbit\\274\\RLD!\\Save001.sav', 'C:\\WGsav\\savprot')
shutil.copy2('C:\\ProgramData\\Orbit\\274\\RLD!\\Save002.sav', 'C:\\WGsav\\savprot')
shutil.copy2('C:\\ProgramData\\Orbit\\274\\RLD!\\saves.ini', 'C:\\WGsav\\savprot')
os.rename('C:\\WGsav\\savprot', 'C:\\WGsav\\{}'.format(name))
time.sleep(300)
应用方法后withdraw
,deiconify
窗口冻结:它不响应命令,按钮,菜单等不起作用。
那么,真正的问题是该怎么做?
这是项目本身,它有一个“project.py”文件,您至少需要 1 个工作 COM 端口
来自 project.py 文件的代码
import serial.tools.list_ports
from tkinter import *
from tkinter import ttk
from Arduino import Arduino
from win32api import GetSystemMetrics, GetMonitorInfo, MonitorFromPoint
import time
monitor_info = GetMonitorInfo(MonitorFromPoint((0,0)))
monitor_area = monitor_info.get("Monitor")
work_area = monitor_info.get("Work")
task_bar = monitor_area[3] - work_area[3]
resx_win = str(int((GetSystemMetrics(0)/2)-(900/2)))
resy_win = str(int((GetSystemMetrics(1)/2)-(700/2) - task_bar))
resx_head = str(int((GetSystemMetrics(0)/2) - 800/2))
resy_head = str(int((GetSystemMetrics(1)/2) - (500/2)- task_bar))
warningx_head = str(int((GetSystemMetrics(0)/2)-300/2))
warningy_head = str(int((GetSystemMetrics(1) / 2) - (200 / 2) - task_bar))
resx_LED = str(int((GetSystemMetrics(0)/2)-950/2))
resy_LED = str(int((GetSystemMetrics(1)/2)-(600/2) - task_bar))
ports = serial.tools.list_ports.comports()
for port, desc, hwid in sorted(ports):
port
head = Tk()
head.geometry('800x500+'+resx_head+'+'+resy_head)
head.title('Лаунчер')
head.resizable(width=False, height=False)
head.wm_attributes('-alpha', 0.95)
custom_bg = PhotoImage(file = 'custom_bg.png',master = head)
head.iconbitmap('window.ico')
def warning_port_baud_def():
warning_port_baud = Toplevel()
warning_port_baud.grab_set()
warning_port_baud.geometry('300x200+' + warningx_head + '+' + warningy_head)
warning_port_baud.title('Ошибка')
warning_port_baud.iconbitmap('mistake.ico')
warning_port_baud.resizable(width=False, height=False)
warning_canvas = Canvas(warning_port_baud, width=300, height=200)
warning_canvas.pack()
warning_port_baud_frame = Frame(warning_port_baud)
warning_port_baud_frame.place(relwidth=1, relheight=1)
warning_port_baud_label = Label(warning_port_baud_frame,text='Введите \nнеобходимые\n значения ' #
'\nдля порта \nи скорости', font= ("message-box",16)) #
warning_port_baud_label.place(x=120, y=20, width=180, height=150) # Окно,вылезающее при
global warning_image # некорректном вводе
warning_image = PhotoImage(file='y_warning.png', master=warning_port_baud_frame) # порта или бодрейта
warning_ico = Label(warning_port_baud_frame, image=warning_image) # Ну и картинка для
warning_ico.place(x=15, y=43) # этого окна
warning_port_baud.mainloop()
def warning_port_def():
warning_port = Toplevel()
warning_port.grab_set()
warning_port.geometry('300x200+' + warningx_head + '+' + warningy_head)
warning_port.title('Ошибка')
warning_port.iconbitmap('mistake.ico')
warning_port.resizable(width=False, height=False)
warning_port_canvas = Canvas(warning_port,width=300, height=200)
warning_port_canvas.pack()
warning_port_frame = Frame(warning_port)
warning_port_frame.place(relwidth=1, relheight=1)
warning_port_label = Label(warning_port_frame, text='Некорректный\nввод порта',font=("message-box", 16)) #
warning_port_label.place(x=120, y=20, width=180, height=150) # Окно,вылезающее при
global warning_image # некорректном вводе
warning_image = PhotoImage(file='y_warning.png', master=warning_port_frame) # порта
warning_ico = Label(warning_port_frame, image=warning_image) # Ну и картинка
warning_ico.place(x=15, y=43)
warning_port.mainloop()
def warning_port_num_def():
warning_port_num = Toplevel()
warning_port_num.grab_set()
warning_port_num.geometry('300x200+' + warningx_head + '+' + warningy_head)
warning_port_num.title('Ошибка')
warning_port_num.iconbitmap('mistake.ico')
warning_port_num.resizable(width=False, height=False)
warning_port_num_canvas = Canvas(warning_port_num,width=300, height=200)
warning_port_num_canvas.pack()
warning_port_num_frame = Frame(warning_port_num)
warning_port_num_frame.place(relwidth=1, relheight=1)
warning_port_num_label = Label(warning_port_num_frame, text='Некорректный\nввод порта:\nукажите '
'его\n номер\n[1,2,3 и т.д.]',font=("message-box", 16)) #
warning_port_num_label.place(x=120, y=20, width=180, height=150) # Окно,вылезающее при
global warning_image # некорректном вводе
warning_image = PhotoImage(file='y_warning.png', master=warning_port_num_frame) # номера порта
warning_ico = Label(warning_port_num_frame, image=warning_image) # Ну и картинка
warning_ico.place(x=15, y=43)
warning_port_num.mainloop()
def warning_port_name_def():
warning_port_name = Toplevel()
warning_port_name.grab_set()
warning_port_name.geometry('300x200+' + warningx_head + '+' + warningy_head)
warning_port_name.title('Ошибка')
warning_port_name.iconbitmap('mistake.ico')
warning_port_name.resizable(width=False, height=False)
warning_port_name_canvas = Canvas(warning_port_name,width=300, height=200)
warning_port_name_canvas.pack()
warning_port_name_frame = Frame(warning_port_name)
warning_port_name_frame.place(relwidth=1, relheight=1)
warning_port_name_label = Label(warning_port_name_frame, text='Некорректный\nввод порта:'
'\nданный порт\nне подключен',font=("message-box", 16)) #
warning_port_name_label.place(x=120, y=20, width=180, height=150) # Окно,вылезающее при
global warning_image # некорректном вводе
warning_image = PhotoImage(file='y_warning.png', master=warning_port_name_frame) # порта
warning_ico = Label(warning_port_name_frame, image=warning_image) # Ну и картинка
warning_ico.place(x=15, y=43)
warning_port_name.mainloop()
def warning_baud_def():
warning_baud = Toplevel()
warning_baud.grab_set()
warning_baud.geometry('300x200+' + warningx_head + '+' + warningy_head)
warning_baud.title('Ошибка')
warning_baud.iconbitmap('mistake.ico')
warning_baud.resizable(width=False, height=False)
warning_baud_canvas = Canvas(warning_baud,width=300, height=200)
warning_baud_canvas.pack()
warning_baud_frame = Frame(warning_baud)
warning_baud_frame.place(relwidth=1, relheight=1)
warning_baud_label = Label(warning_baud_frame, text='Некорректный\nввод бодрейта:\nиспользуйте\nцифры',font=("message-box", 16)) #
warning_baud_label.place(x=120, y=20, width=180, height=150) # Окно,вылезающее при
global warning_image # некорректном вводе
warning_image = PhotoImage(file='y_warning.png', master=warning_baud_frame) # порта
warning_ico = Label(warning_baud_frame, image=warning_image) # Ну и картинка
warning_ico.place(x=15, y=43)
warning_baud.mainloop()
def warning_baud_min_def():
warning_baud_min = Toplevel()
warning_baud_min.grab_set()
warning_baud_min.geometry('300x200+' + warningx_head + '+' + warningy_head)
warning_baud_min.title('Ошибка')
warning_baud_min.iconbitmap('mistake.ico')
warning_baud_min.resizable(width=False, height=False)
warning_baud_min_canvas = Canvas(warning_baud_min,width=300, height=200)
warning_baud_min_canvas.pack()
warning_baud_min_frame = Frame(warning_baud_min)
warning_baud_min_frame.place(relwidth=1, relheight=1)
warning_baud_min_label = Label(warning_baud_min_frame, text='Некорректный\nввод бодрейта\nМинимум: 300',font=("message-box", 16)) #
warning_baud_min_label.place(x=120, y=20, width=180, height=150) # Окно,вылезающее при
global warning_image # некорректном вводе
warning_image = PhotoImage(file='y_warning.png', master=warning_baud_min_frame) # порта
warning_ico = Label(warning_baud_min_frame, image=warning_image) # Ну и картинка
warning_ico.place(x=15, y=43)
warning_baud_min.mainloop()
def port_OlO_def():
port_OlO = Toplevel()
port_OlO.geometry('300x200+' + warningx_head + '+' + warningy_head)
port_OlO.title('Ошибка')
port_OlO.resizable(width=False, height=False)
port_OlO.iconbitmap('mistake.ico')
port_OlO_frame = Frame(port_OlO)
port_OlO_frame.place(relwidth=1, relheight=1)
port_OlO_label = Label(port_OlO_frame, text='Издеваетесь?',font=("message-box", 16))
port_OlO_label.place(x=120, y=20, width=180, height=150)
global warning_image
warning_image = PhotoImage(file='y_warning.png', master=port_OlO_frame)
warning_ico = Label(port_OlO_frame, image=warning_image)
warning_ico.place(x=15, y=43)
port_OlO.mainloop()
###################################
def Win():
head.withdraw()
win = Toplevel()
win.geometry('900x700+' + resx_win + '+' + resy_win)
win.title('Набор')
win["bg"] = "#a17a86"
win.iconbitmap('window.ico')
win.resizable(width=False, height=False)
win.protocol("WM_DELETE_WINDOW", lambda: head.destroy()) # Закрывает окно head,при закрытии этого
frame_lobby = Frame(win)
frame_lobby.place(relwidth = 1,relheight = 1)
frame_lobby.configure(background = "#FFAEC2")
LED_bg = PhotoImage(file = 'LED_bg.png')
LCD_bg = PhotoImage(file = 'LCD_bg.png')
buzzer_bg = PhotoImage(file = 'buzzer_bg.png')
ultrasound_bg = PhotoImage(file = 'ultrasound_bg.png')
servo_bg = PhotoImage(file = 'servo_bg.png')
DS18B20_bg = PhotoImage(file = 'DS18B20_bg.png')
help_button_image = PhotoImage(file = 'help_button_image.png')
help_button_image_small = help_button_image.subsample(85, 85)
def LED_window_def():
win.withdraw()
LED_window = Toplevel()
LED_window.grab_set()
LED_window.geometry('950x600+{}+{}'.format(resx_LED,resy_LED))
LED_window.title("Светодиод")
LED_window.resizable(width=False, height=False)
LED_window.protocol("WM_DELETE_WINDOW", lambda: head.destroy())
LED_frame = Frame(LED_window)
LED_frame.place(relwidth = 1,relheight = 1)
LED_frame.configure(background = "")
LED_button_on_off = Label(LED_frame,text = 'Тут будет гифка ON/OFF')
LED_button_on_off.place(x = 30,y = 120,width = 200,height = 130)
LED_button_on_off_str = Label(LED_frame, text='Тут будет гифка ON/OFF--STR')
LED_button_on_off_str.place(x = 260,y = 120,width = 200,height = 130)
LED_button_bright = Label(LED_frame,text = 'Яркость (ШИМ со шкалой)')
LED_button_bright.place(x = 490,y = 120,width = 200,height = 130)
LED_button_bright_POT = Label(LED_frame,text = 'Яркость(потенциометр)')
LED_button_bright_POT.place(x = 720,y = 120,width = 200,height = 130)
tut_budet_bg = Label(LED_frame,text = 'Тут будет <BG>')
tut_budet_bg.place(x = 325,y = 0 ,width = 300,height = 80)
help_button = ttk.Button(LED_frame,text = 'Условие',image = help_button_image_small,compound = LEFT,)
help_button_style = ttk.Style(head)
help_button_style.configure('TButton', font=('lucida console', '15'),background = '#fafad2')
help_button.place(x = 760,y = 15,width = 140,height = 45)
def undo():
win.deiconify()
LED_window.withdraw()
undo_LED_button = ttk.Button(LED_frame,text = 'Назад',command = undo)
undo_LED_button.place(width = 100,height = 45)
LED_button = Button(frame_lobby,image = LED_bg,command = LED_window_def)
LED_button.place(x = 50,y = 20)
ultrasound_button = Button(frame_lobby, image=ultrasound_bg)
ultrasound_button.place(x = 50,y = 245)
LCD_button = Button(frame_lobby,image = LCD_bg)
LCD_button.place(x = 50,y = 470)
buzzer_button = Button(frame_lobby,image = buzzer_bg)
buzzer_button.place(x = 475,y= 20)
servo_button = Button(frame_lobby,image = servo_bg)
servo_button.place(x = 475,y = 245)
DS18B20_button = Button(frame_lobby,image = DS18B20_bg)
DS18B20_button.place(x = 475,y = 470)
win.mainloop()
def WinSon():
port_ch = (var_p.get()) #
if port_ch == PortList[0]: # Если в меню не выбран порт,
port_ch = entry_p.get() # читает поле ввода
print(port_ch) #
baudrate = (var_bd.get()) #
if baudrate == BaudList[0]: # То же самое,
baudrate = entry_bd.get() # только уже с бодрейтом
print(baudrate) #
index = port_ch.find("COM")
if len(port_ch) == 0 or len(baudrate) == 0: #
print(len(port_ch)) # Проверка на длину введённых данных
print(len(baudrate)) # <Потом добавлю поиск подстроки 'COM'>
warning_port_baud_def() #
elif index == -1:
warning_port_def()
elif baudrate.isdigit() == False:
warning_baud_def()
elif int(baudrate) < 300:
warning_baud_min_def()
elif port_ch == 'COM':
warning_port_num_def()
elif port_ch != port:
warning_port_name_def()
else:
Win()
frame = Frame(head)
frame.place(relwidth = 1,relheight = 1)
bg = PhotoImage(file = 'bg_800x500.png') #
wallpaper = Label(frame,image = bg) # Пикча для BG
wallpaper.pack() #
t_p = ttk.Label(frame, text='ПОРТ/выбери или напиши', background='#A52A2A',
font = ('lucida console','14'),anchor = CENTER)
t_p.place(x=20, y = 220, width = 370, height = 60)
PortList = ['Выберите порт', port]
var_p = StringVar(frame)
var_p.set(PortList[0])
opt_p = ttk.OptionMenu(frame, var_p, *PortList)
opt_p.place(x=20, y=280, width=185, height=30)
entry_p = Entry(frame,font = 15)
entry_p.place(x = 205,y = 280,width = 185,height = 30)
t_bd = ttk.Label(frame,text = 'БОДРЕЙТ указанный в \nскетче ардуино|выбери или напиши',
background = '#A52A2A',font = ('lucida console','14'),anchor = CENTER)
t_bd.place(x = 410,y = 220,width = 370,height = 60)
BaudList = ['Выберите скорость',300,1200,2400,4800,9600,19200,38400,57600,74880,115200]
var_bd = StringVar(frame)
var_bd.set(BaudList[0])
opt_bd = ttk.OptionMenu(frame, var_bd, *BaudList)
opt_bd.place(x = 410,y = 280,width = 185,height = 30)
entry_bd = Entry(frame, font=15)
entry_bd.place(x=595, y=280, width=185, height=30)
further = PhotoImage(file = 'далее.png')
small_further = further.subsample(15, 15)
further_Button_style = ttk.Style(head)
further_Button_style.configure('TButton',font = ('lucida console','15'))
further_Button = ttk.Button(frame,text = 'Далее',image = small_further,
compound = LEFT,style = 'TButton',command = WinSon) # WinSon
further_Button.place(x = 350,y = 370,width = 130,height = 50)
head.mainloop()
例如弹出窗口。如果它的副本已经打开,我如何防止在单击它时打开它?
最原始的例子:
from tkinter import *
head = Tk()
head.geometry('800x500')
head.title('Лаунчер')
def new_window():
win = Tk()
win.geometry('300x200')
win.title('Ошибка')
win_frame = Frame(new_window)
win_frame.place(relwidth=1, relheight=1)
win.mainloop()
frame = Frame(head)
frame.place(relwidth = 1,relheight = 1)
button = Button(frame,text = 'Далее',command = new_window)
button.place(x = 350,y = 370,width = 130,height = 50)
head.mainloop()
my.py是所需的文件。
选择波特率后,需要将 \Arduino\prototype.ino 代码上传到 arduino(第 407 行)
整个代码:
import serial.tools.list_ports
from tkinter import *
from Arduino import Arduino
from win32api import GetSystemMetrics
import time
resx_win = str(int((GetSystemMetrics(0)/2)-(800/2)-9)) #
resy_win = str(int((GetSystemMetrics(1)/2)-(500/2)-35)) #
resx_head = str(int((GetSystemMetrics(0)/2) - (800/2)-9)) # Переменные для расположения окон посередине экрана
resy_head = str(int((GetSystemMetrics(1)/2) - (500/2)-35)) #
warningx_head = str(int((GetSystemMetrics(0)/2)-(300/2)-9)) #
warningy_head = str(int((GetSystemMetrics(1)/2) - (200/2)-35)) #
ports = serial.tools.list_ports.comports() #
for port, desc, hwid in sorted(ports): # Инициализация портов(разделение строки
port # состоящей из нескольких портов ещё не делал)
# <Работает в тестовом режиме>
head = Tk()
head.geometry('800x500+'+resx_head+'+'+resy_head)
head.title('Лаунчер')
head.resizable(width=False, height=False)
head.wm_attributes('-alpha', 0.95)
def warning_port_baud_def():
warning_port_baud = Tk()
warning_port_baud.geometry('300x200+' + warningx_head + '+' + warningy_head)
warning_port_baud.title('Ошибка')
warning_canvas = Canvas(warning_port_baud, width=300, height=200)
warning_canvas.pack()
warning_port_baud_frame = Frame(warning_port_baud)
warning_port_baud_frame.place(relwidth=1, relheight=1)
warning_port_baud_label = Label(warning_port_baud_frame,text='Введите \nнеобходимые\n значения ' #
'\nдля порта \nи скорости', font= ("message-box",16)) #
warning_port_baud_label.place(x=120, y=20, width=180, height=150) # Окно,вылезающее при
global warning_image # некорректном вводе
warning_image = PhotoImage(file='y_warning.png', master=warning_port_baud_frame) # порта или бодрейта
warning_ico = Label(warning_port_baud_frame, image=warning_image) # Ну и картинка для
warning_ico.place(x=15, y=43) # этого окна
def WinSon():
port_ch = (var_p.get()) #
if port_ch == PortList[0]: # Если в меню не выбран порт,
port_ch = entry_p.get() # читает поле ввода
print(port_ch) #
baudrate = (var_bd.get()) #
if baudrate == BaudList[0]: # То же самое,
baudrate = entry_bd.get() # только уже с бодрейтом
print(baudrate) #
if len(port_ch) or len(baudrate) == 0: #
print(len(port_ch)) # Проверка на длину введённых данных
print(len(baudrate)) # <Потом добавлю поиск подстроки 'COM'>
warning_port_baud_def() #
board = Arduino(baudrate, port= port_ch) # Инициализация ардуинки и её порта и скорости
board.pinMode(13, "OUTPUT") # Добавил,пока,просто так
head.withdraw()
win = Toplevel()
win.geometry('800x500+' + resx_win + '+' + resy_win)
win.title('Набор')
win.protocol("WM_DELETE_WINDOW", lambda: head.destroy()) # Закрывает окно head,при открытии этого
canvas2 = Canvas(win,width = 800,height = 500)
canvas2.pack()
frame_lobby = Frame(win)
frame_lobby.place(relwidth = 1,relheight = 1)
win.mainloop()
canvas = Canvas(head,width = 800,height = 500)
canvas.pack()
frame = Frame(head)
frame.place(relwidth = 1,relheight = 1)
bg = PhotoImage(file = 'bg_800x500.png') #
wallpaper = Label(frame,image = bg) # Пикча для BG
wallpaper.pack() #
t_p = Label(frame, text='ПОРТ/выбери или напиши', bg='#A52A2A',font = 20) #
t_p.place(x=20, y = 220, width = 370, height = 60) #
PortList = ['Выберите порт', port] #
var_p = StringVar(frame) # Меню для порта
var_p.set(PortList[0]) #
opt_p = OptionMenu(frame, var_p, *PortList) #
opt_p.place(x=20, y=280, width=185, height=30) #
entry_p = Entry(frame,font = 15) # Поле ввода для порта
entry_p.place(x = 205,y = 280,width = 185,height = 30) #
t_bd = Label(frame,text = 'БОДРЕЙТ указанный в \nскетче ардуино/выбери или напиши', #
bg = '#A52A2A',font = 20) #
t_bd.place(x = 410,y = 220,width = 370,height = 60) #
BaudList = ['Выберите скорость',9600,19200,38400,57600,115200] # Меню для бодрейта
var_bd = StringVar(frame) #
var_bd.set(BaudList[0]) #
opt_bd = OptionMenu(frame, var_bd, *BaudList) #
opt_bd.place(x = 410,y = 280,width = 185,height = 30) #
entry_bd = Entry(frame, font=15,bd = 3) # Поле ввода для бодрейта
entry_bd.place(x=595, y=280, width=185, height=30) #
further = PhotoImage(file = 'далее.png') #
small_further = further.subsample(15, 15) # Кнопка и картинка
further_Button = Button(frame,text = 'Далее',image = small_further, # выполняет команду
compound = LEFT,font = ("lucida console", 16),bd = 5,command = WinSon) # WinSon
further_Button.place(x = 350,y = 370,width = 130,height = 50) #
head.mainloop()
条件本身
if len(port_ch) or len(baudrate) == 0: #
print(len(port_ch)) # Проверка на длину введённых данных
print(len(baudrate)) # <Потом добавлю поиск подстроки 'COM'>
warning_port_baud_def() #
需要帮助...有必要从 OptionMenu 中获取有关所选参数(PORT、BAUDRATE)的数据并将其写入变量,以便稍后在此行中使用它
board = Arduino("115200", port=("COM5"))
这是相关的代码片段
import serial.tools.list_ports
import tkinter
from tkinter import *
from Arduino import Arduino
import time
ports = serial.tools.list_ports.comports()
for port, desc, hwid in sorted(ports):
port
board = Arduino("115200", port=("COM5"))
head = Tk()
head.geometry('500x300')
head.title('Лаунчер')
head.resizable(width = False,height = False)
head.wm_attributes('-alpha',0.95)
def WinSon():
head.withdraw()
win = Toplevel()
win.geometry('800x500')
win.title('Набор')
win.protocol("WM_DELETE_WINDOW", lambda: head.destroy())
win.mainloop()
canvas = Canvas(head,width = 500,height = 300)
canvas.pack()
frame = Frame(head)
frame.place(relwidth = 1,relheight = 1)
t_p = Label(frame, text='ПОРТ', bg='#A52A2A')
t_p.place(x=65, y=150, width=150, height=30)
PortList = ['Выберите порт', port]
var_p = StringVar(frame)
var_p.set(PortList[0])
opt_p = OptionMenu(frame, var_p, *PortList)
opt_p.place(x=65, y=180, width=150, height=30)
t_bd = Label(frame,text = 'БОДРЕЙТ',bg = '#A52A2A')
t_bd.place(x = 285,y = 150,width = 150,height = 30)
BaudList = ['Выберите скорость',9600,19200,38400,57600,115200]
var_bd = StringVar(frame)
var_bd.set(BaudList[0])
opt_bd = OptionMenu(frame, var_bd, *BaudList)
opt_bd.place(x = 285,y = 180,width = 150,height = 30)
Redo_Button = Button(frame,text = 'Далее',font = ("lucida console", 20,),command = WinSon)
Redo_Button.place(x = 192.5,y = 230)
head.mainloop()