как сделать кнопку не активной?
есть две кнопки, одна расчет, вторая вывод графика. Как сделать кнопку вывода графика не активной до того пока не будет сделан расчет? расчет идет по двум выбираемым параметрам. и например сделан расчет по одному параметру и по нему же строится график, а если переключаем на второй параметр и нажимаем кнопку вывода графика то он идет по первому расчету. Надеюсь понятно объяснил. У меня две программы, одна по алгоритму, вторая по интерфейсу, интерфейс делал в qt designer ui формат. Библиотtка PyQT6 Код алгоритма:
from PyQt6 import QtCore, QtGui, QtWidgets
from interface20 import * #интерфейс
from PyQt6.QtGui import QMovie
from PyQt6.QtWidgets import QFileDialog
from tkinter import messagebox
import numpy as np
import matplotlib.pyplot as plt
import sys
import math
from matplotlib import mlab
from scipy import interpolate
from matplotlib.patches import *
from scipy.optimize import fsolve
from matplotlib.patches import Arc
from bisect import bisect_left
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
def soplo_profil():
def bell_nozzle(k, aratio, Rt, l_percent): # вычисления геометрических параметров сопла
entrant_angle = -135 # upto the nozzle designer, usually -135
ea_radian = math.radians(entrant_angle)
l_percent = 80 # nozzle length percntage upto the nozzle designer, usually 80
Lnp = 0.8
angles = find_wall_angles(aratio, throat_radius, l_percent) # find wall angles (theta_n, theta_e) for given aratio (ar)
nozzle_length = angles[0]; theta_n = angles[1]; theta_e = angles[2];
data_intervel = 100
# throat entrant section / скругление входа в критику
ea_start = ea_radian # where: −135 ≤ θ ≤ −90 (The initial angle is typical -135 degrees)
ea_end = -math.pi/2 # where: −135 ≤ θ ≤ −90
angle_list = np.linspace(ea_start, ea_end, data_intervel)
xe = []; ye = [];
for i in angle_list:
xe.append( 1.5 * Rt * math.cos(i) )
ye.append( 1.5 * Rt * math.sin(i) + 2.5 * Rt )
#exit section / скругление выхода из критики
ea_start = -math.pi/2 # where: −90 ≤ θ ≤ (θn − 90)
ea_end = theta_n - math.pi/2 # where: −90 ≤ θ ≤ (θn − 90)
angle_list = np.linspace(ea_start, ea_end, data_intervel)
xe2 = []; ye2 = [];
for i in angle_list:
xe2.append( 0.382 * Rt * math.cos(i) )
ye2.append( 0.382 * Rt * math.sin(i) + 1.382 * Rt )
# bell section / параболическая секция
Nx = 0.382 * Rt * math.cos(theta_n - math.pi/2) # Nx, Ny-N is defined by [Eqn. 5] setting the angle to (θn – 90)
Ny = 0.382 * Rt * math.sin(theta_n - math.pi/2) + 1.382 * Rt # Nx, Ny-N is defined by [Eqn. 5] setting the angle to (θn – 90)
Ex = Lnp * ( (math.sqrt(aratio) - 1) * Rt )/ math.tan(math.radians(15) ) # Ex - [Eqn. 3], and coordinate Ey - [Eqn. 2]
Ey = math.sqrt(aratio) * Rt # Ex - [Eqn. 3], and coordinate Ey - [Eqn. 2]
m1 = math.tan(theta_n); m2 = math.tan(theta_e); # gradient m1,m2 - [Eqn. 8]
C1 = Ny - m1*Nx; C2 = Ey - m2*Ex; # intercept - [Eqn. 9]
Qx = (C2 - C1)/(m1 - m2) # intersection of these two lines (at point Q)-[Eqn.10]
Qy = (m1*C2 - m2*C1)/(m1 - m2) # intersection of these two lines (at point Q)-[Eqn.10]
int_list = np.linspace(0, 1, data_intervel)
xbell = []; ybell = [];
for t in int_list: # the bell is a quadratic Bézier curve, which has equations
xbell.append( ((1-t)**2)*Nx + 2*(1-t)*t*Qx + (t**2)*Ex )
ybell.append( ((1-t)**2)*Ny + 2*(1-t)*t*Qy + (t**2)*Ey )
# create negative values for the other half of nozzle / создание значений для второй половины профиля
nye = [ -y for y in ye]
nye2 = [ -y for y in ye2]
nybell = [ -y for y in ybell]
return angles, (xe, ye, nye, xe2, ye2, nye2, xbell, ybell, nybell)
def find_wall_angles(ar, Rt, l_percent): # определение углов θn и θe в зависимости от aratio по графикам эмпирических данных
aratio = [ 4, 5, 10, 20, 30, 40, 50, 100]
theta_n_60 = [20.5, 20.5, 16.0, 14.5, 14.0, 13.5, 13.0, 11.2]
theta_n_80 = [21.5, 23.0, 26.3, 28.8, 30.0, 31.0, 31.5, 33.5]
theta_n_90 = [20.0, 21.0, 24.0, 27.0, 28.5, 29.5, 30.2, 32.0]
theta_e_60 = [26.5, 28.0, 32.0, 35.0, 36.2, 37.1, 35.0, 40.0]
theta_e_80 = [14.0, 13.0, 11.0, 9.0, 8.5, 8.0, 7.5, 7.0]
theta_e_90 = [11.5, 10.5, 8.0, 7.0, 6.5, 6.0, 6.0, 6.0]
# nozzle length / длина сопла
f1 = ( (math.sqrt(ar) - 1) * Rt )/ math.tan(math.radians(15) )
theta_n = theta_n_80; theta_e = theta_e_80;
Ln = 0.8 * f1
global len_nozzle
len_nozzle = Ln
# find the nearest ar index in the aratio list
x_index, x_val = find_nearest(aratio, ar)
# if the value at the index is close to input, return it
if round(aratio[x_index], 1) == round(ar, 1):
return Ln, math.radians(theta_n[x_index]), math.radians(theta_e[x_index])
# check where the index lies, and slice accordingly
if (x_index>2):
# slice couple of middle values for interpolation
ar_slice = aratio[x_index-2:x_index+2]
tn_slice = theta_n[x_index-2:x_index+2]
te_slice = theta_e[x_index-2:x_index+2]
# find the tn_val for given ar
tn_val = interpolate(ar_slice, tn_slice, ar)
te_val = interpolate(ar_slice, te_slice, ar)
elif( (len(aratio)-x_index) <= 1):
# slice couple of values initial for interpolation
ar_slice = aratio[x_index-2:len(x_index)]
tn_slice = theta_n[x_index-2:len(x_index)]
te_slice = theta_e[x_index-2:len(x_index)]
# find the tn_val for given ar
tn_val = interpolate(ar_slice, tn_slice, ar)
te_val = interpolate(ar_slice, te_slice, ar)
else:
# slice couple of end values for interpolation
ar_slice = aratio[0:x_index+2]
tn_slice = theta_n[0:x_index+2]
te_slice = theta_e[0:x_index+2]
# find the tn_val for given ar
tn_val = interpolate(ar_slice, tn_slice, ar)
te_val = interpolate(ar_slice, te_slice, ar)
return Ln, math.radians(tn_val), math.radians(te_val)
def interpolate(x_list, y_list, x): # функция интерполяции для определения углов θn и θe по графикам эмпирических данных
if any(y - x <= 0 for x, y in zip(x_list, x_list[1:])):
raise ValueError("x_list must be in strictly ascending order!")
intervals = zip(x_list, x_list[1:], y_list, y_list[1:])
slopes = [(y2 - y1) / (x2 - x1) for x1, x2, y1, y2 in intervals]
if x <= x_list[0]:
return y_list[0]
elif x >= x_list[-1]:
return y_list[-1]
else:
i = bisect_left(x_list, x) - 1
return y_list[i] + slopes[i] * (x - x_list[i])
def find_nearest(array, value): # функция поиска ближайшего значения для определения углов θn и θe по графикам эмпирических данных
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx, array[idx]
def plot_nozzle(ax, title, Rt, angles, contour): # построение профиля сопла с размерами
# wall angles
nozzle_length = angles[0]; theta_n = angles[1]; theta_e = angles[2];
# contour values
xe = contour[0]; ye = contour[1]; nye = contour[2];
xe2 = contour[3]; ye2 = contour[4]; nye2 = contour[5];
xbell = contour[6]; ybell = contour[7]; nybell = contour[8];
# set correct aspect ratio
ax.set_aspect('equal')
# throat enterant
ax.plot(xe, ye, linewidth=2.5, color='g')
ax.plot(xe, nye, linewidth=2.5, color='g')
# chamder exit
Sx = xe[0]
Sy = ye[0]
Sny = nye[0]
Ex = Sx - (R - Sy)
Ey = R
Eny = -R
linex = [Sx, Ex]
liney = [Sy, Ey]
lineny = [Sny, Eny]
ax.plot(linex, liney, linewidth=2.5, color='k') # выход из камеры сгорания
ax.plot(linex, lineny, linewidth=2.5, color='k') # выход из камеры сгорания
# throat inlet line
x1 = linex[1]; y1 = 0;
x2 = linex[1]; y2 = R;
#dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
# draw arrow, inlet radial line [x1, y1] to [x2, y2]
text = ' Rch = ' + str(R)
ax.plot(x1, 0, '+', color='k' )
# draw dimension from [x1, y1] to [x2, y2]
ax.annotate( "", [x1, y1], [x2, y2] , arrowprops=dict(lw=0.5, arrowstyle='<-') )
ax.text((x1+x2)/2, R/2, text, fontsize=9 )
# nozzle inlet length line [0,0] to [xe[0], 0]
text = ' Li = ' + str( round( abs(linex[1]), 1) )
#ax.plot(0,0, '+' )
# draw dimension from [0,0] to [xe[0], 0]
ax.annotate( "", [0,0], [linex[1], 0], arrowprops=dict(lw=0.5, arrowstyle='<->') )
ax.text( linex[1]/2, Rt/15, text, ha='center', fontsize=9 )
global Li
Li = abs(linex[1])
# find mid point and draw arc radius
i = int(len(xe)/2)
xcenter = 0; ycenter = 2.5 * Rt;
xarch = xe[i]; yarch = ye[i]
# draw arrow, enterant radial line [xcenter, ycenter] to [xarch, yarch]
text = 'Ri = '+ str( round( 1.5 * Rt, 1 ) )
ax.plot(xcenter, ycenter, '+', color='g' )
# draw dimension from [xcenter, ycenter] to [xarch, yarch]
ax.annotate( "", [xcenter, ycenter], [xarch, yarch], arrowprops=dict(lw=0.5, arrowstyle='<-') )
ax.text(Rt/15, ycenter, text, fontsize=9 )
###ax.plot(xe2, ye2, linewidth=0.5, color='r')
# throat radius line [0,0] to [xe[-1], ye[-1]]
text = ' Rt = '+ str(Rt)
ax.plot(0, 0, '+', color='r' )
# draw dimension from [0,0] to [xe[-1], ye[-1]]
ax.annotate( "", [0,0], [xe[-1], nye[-1]], arrowprops=dict(lw=0.5, arrowstyle='<-') )
ax.text( xe[-1]/2, nye[-1]/2, text, fontsize=9 )
# throat exit
ax.plot(xe2, ye2, linewidth=2.5, color='r')
ax.plot(xe2, nye2, linewidth=2.5, color='r')
# find mid point and draw arc radius
i = int(len(xe2)/2)
xcenter2 = 0; ycenter2 = 1.382 * Rt;
xarch2 = xe2[i]; yarch2 = ye2[i]
# draw arrow, exit radial line from [xcenter2,ycenter2] to [xarch2, yarch2]
text = 'Rn = '+ str( round(0.382 * Rt,1) )
ax.plot(xcenter2, ycenter2, '+', color='r' )
# draw dimension from [xcenter2,ycenter2] to [xarch2, yarch2]
ax.annotate( "", [xcenter2,ycenter2], [xarch2, yarch2], arrowprops=dict(lw=0.5, arrowstyle='<-') )
ax.text(Rt/15, ycenter2, text, fontsize=9 )
# bell section
ax.plot(xbell, ybell, linewidth=2.5, color='b')
ax.plot(xbell, nybell, linewidth=2.5, color='b')
# throat radius line [0,0] to [xe[-1], ye[-1]]
text = ' Re = ' + str( round( (math.sqrt(aratio) * Rt), 1) )
ax.plot(xbell[-1],0, '+', color='blue' )
# draw dimension from [0,0] to [xe[-1], ye[-1]]
ax.annotate( "", [xbell[-1],0], [xbell[-1], ybell[-1]], arrowprops=dict(lw=0.5, arrowstyle='<-') )
ax.text( (xbell[-1] - Rt/15), ybell[-1]/2, text, ha='right', fontsize=9 )
# nozzle length line [0,0] to [xe[-1], ye[-1]]
text = ' Ln = ' + str( round( nozzle_length, 1) )
#ax.plot(0,0, '+' )
# draw dimension from [0,0] to [xbell[-1], 0]
ax.annotate( "", [0,0], [xbell[-1], 0], arrowprops=dict(lw=0.5, arrowstyle='<->') )
ax.text( xbell[-1]/2, Rt/15, text, ha='center', fontsize=9 )
# axis
#ax.axhline(color='black', lw=0.5, linestyle="dashed")
ax.axvline(color='black', lw=0.5, linestyle="dashed")
# grids
ax.grid()
ax.minorticks_on()
ax.grid(which='major', linestyle='-', linewidth='0.5') # , color='red'
ax.grid(which='minor', linestyle=':', linewidth='0.5') # , color='black'
# show
plt.title(title, fontsize=9)
global theta_n_deg
theta_n_deg = math.degrees(theta_n)
global theta_e_deg
theta_e_deg = math.degrees(theta_e)
# draw theta_n, throat inflexion angle
adj_text = 0
origin = [ xe2[-1], nye2[-1]-adj_text ]
degree_symbol = r'$\theta$n'
draw_angle_arc(ax, theta_n, origin, degree_symbol )
# draw theta_n, throat exit angle
origin = [ xbell[-1], nybell[-1] ]
degree_symbol = r'$\theta$e'
draw_angle_arc(ax, theta_e, origin, degree_symbol )
return
def draw_angle_arc(ax, theta_n, origin, degree_symbol=r'$\theta$'): # функция отображения дуги для построения профиля сопла
length = 30
# start point
startx = origin[0]; starty = origin[1];
# find the end point
endx = startx + np.cos(-theta_n) * length #* 0.5
endy = starty + np.sin(-theta_n) * length #* 0.5
# draw the angled line / наклонная линия
ax.plot([startx,endx], [starty,endy], linewidth=0.5, color='k')
# horizontal line
ax.hlines(y=starty, xmin=startx, xmax=startx+length, linewidth=0.5, color='k')
# angle
#arc_obj = Arc([startx, starty], r1, r1, 0, -math.degrees(theta_n), 0, color='k' ) # попробовать откомментить после отладки
#ax.add_patch(arc_obj) # попробовать откомментить после отладки
ax.text(startx+r1/15, starty+r1/15, degree_symbol + ' = ' + str(round(math.degrees(theta_n),1)) + u"\u00b0")
return
def ring(r, h, a=0, n_theta=30, n_height=10): # ring of radius r, height h, base point a
theta = np.linspace(0, 2*np.pi, n_theta)
v = np.linspace(a, a+h, n_height )
theta, v = np.meshgrid(theta, v)
x = r*np.cos(theta)
y = r*np.sin(theta)
z = v
return x, y, z
def plot(title, throat_radius, angles, contour): # график
fig = plt.figure()
ax1 = fig.add_subplot()
plot_nozzle(ax1, title, throat_radius, angles, contour)
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
#plt.show()
plt.clf()
plt.close()
return
#-INPUT MANDATORY DATA---------------------------------------------------
k = float(ui.doubleSpinBox_45.text().replace(',', '.')) # показатель адиабаты
d1 = float(ui.doubleSpinBox_44.text().replace(',', '.')) # диаметр критики
D = float(ui.doubleSpinBox_48.text().replace(',', '.')) # диаметр камеры сгорания
#-CHECK-------------------------------------------------------------------
if d1 >= D:
messagebox.showerror("Ошибка", "Диаметр критического сечения не может быть равен или больше значения диаметра камеры сгорания!")
return
if ui.radioButton_2.isChecked():
#-INPUT GEOMETRY DATA----------------------------------------------------
d2 = float(ui.doubleSpinBox_46.text().replace(',', '.')) # диаметр среза сопла
#-CHECK-------------------------------------------------------------------
if d1 >= d2:
messagebox.showerror("Ошибка", "Диаметр критического сечения не может быть равен или больше значения диаметра выходного сечения!")
return
#-------------------------------------------------------------------------
# initializing variables
r1 = d1 / 2 # радиус критики
r2 = d2 / 2 # радиус среза сопла
R = D / 2 # радиус камеры сгорания
throat_radius = r1
aratio = r2**2 / r1**2
l_percent = 80 # nozzle length percentage upto the nozzle designer, usually 80
def nc_from_eps_c(p_c, p_e, k): # вычисление геометрической степени расширения сопла от степени расширения по давлению
FaFkr = ((k + 1) / 2)**(1 / (k - 1)) \
* (p_e / p_c)**(1 / k) \
* ((k + 1) / (k - 1)*( 1 - (p_e / p_c)**((k -1) / k)))**0.5
nc = 1/FaFkr
return nc
def eps_c_from_nc(nc, k): # вычисление степени расширения сопла по давлению от геометрической степени расширения
pressure_ratio = fsolve(lambda x: nc - nc_from_eps_c(1., x, k), x0=1e-3 / nc)[0]
assert pressure_ratio < 1
return pressure_ratio
eps_c = 1 / eps_c_from_nc(aratio, k) # степень расширения сопла по давлению
#-CHECK-------------------------------------------------------------------
if eps_c >= 500:
messagebox.showerror("Ошибка", "Вводимые значение превышают экспериментальный диапазон!")
return
#-------------------------------------------------------------------------
#------------------------------CALCULATIONS-------------------------------
angles, contour = bell_nozzle(k, aratio, throat_radius, l_percent)
ui.label_26.setText('')
ui.label_27.setText('')
ui.label_28.setText('')
ui.label_32.setText('')
elif ui.radioButton_3.isChecked():
#-INPUT PRESSURE DATA----------------------------------------------------
P = float(ui.doubleSpinBox_47.text().replace(',', '.')) # давление в камере сгорания
H = float(ui.comboBox.currentText().replace(',', '.')) # наружное давление
# height to ambient presure / значение наружного давление в зависимости от высоты / берем давление на половине высоты Н из ГОСТ 4401-81
if H == 1 : P_a = 95461
if H == 2 : P_a = 89876
if H == 3 : P_a = 84559.7
if H == 4 : P_a = 79501
if H == 5 : P_a = 74692
if H == 6 : P_a = 70121
if H == 7 : P_a = 65780
if H == 8 : P_a = 61660
if H == 9 : P_a = 57732
if H == 10 : P_a = 54048
if H == 11 : P_a = 50539
if H == 12 : P_a = 47218
if H == 13 : P_a = 44076
if H == 14 : P_a = 41105
if H == 15 : P_a = 38299.7
if H == 16 : P_a = 35652
if H == 17 : P_a = 33154
if H == 18 : P_a = 30801
if H == 19 : P_a = 28585
if H == 20 : P_a = 26499.9
if H == 21 : P_a = 24540
if H == 22 : P_a = 22699.9
if H == 23 : P_a = 20985
if H == 24 : P_a = 19399
if H == 25 : P_a = 17934
if H == 26 : P_a = 16579.6
if H == 27 : P_a = 15328
if H == 28 : P_a = 14170
if H == 29 : P_a = 13101
if H == 30 : P_a = 12112
if H == 31 : P_a = 11198
if H == 32 : P_a = 10353
if H == 33 : P_a = 9572
if H == 34 : P_a = 8850
if H == 35 : P_a = 8182
if H == 36 : P_a = 7565
if H == 37 : P_a = 6995
if H == 38 : P_a = 6467
if H == 39 : P_a = 5980
if H == 40 : P_a = 5529
if H == 41 : P_a = 5113
if H == 42 : P_a = 4730
if H == 43 : P_a = 4375
if H == 44 : P_a = 4047
if H == 45 : P_a = 3746
if H == 46 : P_a = 3467
if H == 47 : P_a = 3209
if H == 48 : P_a = 2972
if H == 49 : P_a = 2752
if H == 50 : P_a = 2549
if H == 51 : P_a = 2362
if H == 52 : P_a = 2188
if H == 53 : P_a = 2028
if H == 54 : P_a = 1880
if H == 55 : P_a = 1743
if H == 56 : P_a = 1616
if H == 57 : P_a = 1499
if H == 58 : P_a = 1390
if H == 59 : P_a = 1290
if H == 60 : P_a = 1197
if H == 61 : P_a = 1111
if H == 62 : P_a = 1031
if H == 63 : P_a = 957
if H == 64 : P_a = 889
if H == 65 : P_a = 826
if H == 66 : P_a = 767
if H == 67 : P_a = 713
if H == 68 : P_a = 663
if H == 69 : P_a = 617
if H == 70 : P_a = 575
if H == 71 : P_a = 535
if H == 72 : P_a = 499
if H == 73 : P_a = 465
if H == 74 : P_a = 433
if H == 75 : P_a = 404
if H == 76 : P_a = 377
if H == 77 : P_a = 352
if H == 78 : P_a = 329
if H == 79 : P_a = 307
if H == 80 : P_a = 287
if H == 81 : P_a = 268
if H == 82 : P_a = 251
if H == 83 : P_a = 235
if H == 84 : P_a = 220
if H == 85 : P_a = 206
if H == 86 : P_a = 193
if H == 87 : P_a = 181
if H == 88 : P_a = 169
if H == 89 : P_a = 159
if H == 90 : P_a = 149
if H == 91 : P_a = 140
if H == 92 : P_a = 131
if H == 93 : P_a = 123
if H == 94 : P_a = 116
if H == 95 : P_a = 109
if H == 96 : P_a = 102
if H == 97 : P_a = 96
if H == 98 : P_a = 90
if H == 99 : P_a = 85
if H == 100 : P_a = 80
#-------------------------------------------------------------------------
# initializing variables
r1 = d1 / 2 # радиус критики
R = D / 2 # радиус камеры сгорания
throat_radius = r1
l_percent = 80 # nozzle length percentage upto the nozzle designer, usually 80
eps_c = P / P_a
#-CHECK-------------------------------------------------------------------
if eps_c >= 500:
messagebox.showerror("Ошибка", "Вводимые значение превышают экспериментальный диапазон!")
return
#-------------------------------------------------------------------------
#------------------------------CALCULATIONS-------------------------------
FaFkr = ((k + 1) / 2)**(1 / (k - 1)) * (P_a / P)**(1 / k) * ((k + 1) / (k - 1)*( 1 - (P_a / P)**((k - 1) / k)))**0.5
aratio = 1/FaFkr
r2 = (aratio * r1 * r1)**0.5
angles, contour = bell_nozzle(k, aratio, throat_radius, l_percent)
ui.label_26.setText('Давление на срезе (Па):')
ui.label_27.setText('Диаметр выходного сечения (м):')
ui.label_28.setText(str(round(P_a, 2)))
ui.label_32.setText(str(round(r2*2, 2)))
#-PLOT-------------------------------------------------------------------
title = 'Оптимизированное по тяге сопло, профилированное по методу Рао (метод парабол)'
plot(title, throat_radius, angles, contour)
ui.label_19.setText(str(round(Li, 2)))
ui.label_35.setText(str(round(len_nozzle, 2)))
ui.label_34.setText(str(round(aratio, 2)))
ui.label_29.setText(str(round(eps_c, 2)))
ui.label_31.setText(str(round(theta_n_deg, 2)))
ui.label_33.setText(str(round(theta_e_deg, 2)))
Ответы (1 шт):
Автор решения: Amgarak
→ Ссылка
Так как самого интерфейса вы не предоставили, вот вам мой небольшой пример:
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QPushButton, QWidget
from PyQt6 import uic
import io
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
# Инициализация пользовательского интерфейса
self.init_ui()
def init_ui(self):
# Загружаем разметку UI из строки
ui_string = '''
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QPushButton" name="button1">
<property name="text">
<string>Button 1</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="button2">
<property name="text">
<string>Button 2</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
'''
# Загружаем UI из строки с использованием loadUiType
Ui_MainWindow, _ = uic.loadUiType(io.StringIO(ui_string))
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# Подключаем слоты (обработчики событий) к сигналам нажатия кнопок
self.ui.button1.clicked.connect(self.on_button1_clicked)
self.ui.button2.clicked.connect(self.on_button2_clicked)
self.ui.button2.setEnabled(False)
def on_button1_clicked(self):
# Делаем кнопку 2 активной и кнопку 1 неактивной
self.ui.button1.setEnabled(False)
self.ui.button2.setEnabled(True)
def on_button2_clicked(self):
# Делаем кнопку 1 активной и кнопку 2 неактивной
self.ui.button1.setEnabled(True)
self.ui.button2.setEnabled(False)
if __name__ == '__main__':
app = QApplication([])
window = MyWindow()
window.show()
app.exec()