Я создал виджет на питоне, используя библиотеку tkinter. Он имеет один выпадающий список
from tkinter import *
from tkinter.ttk import *
import os
import time
import win32api
def f_step():
window=Tk()
style = Style()
style.configure('W.TButton', font =
('calibri', 12, 'bold'),
foreground = 'blue')
s = Style() # Creating style element
s.configure('Wild.TRadiobutton', # First argument is the name of style. Needs to end with: .TRadiobutton
background='bisque2', # Setting background to our specified color above
font = "calibri 10 bold") # You can define colors like this also
window.title('Tool tool')
window.geometry("700x300+10+10")
#window.geometry(side = "top", fill = "both", expand = True)
txt_1=StringVar()
lbl_1 = Label(window,text = "Are result files same", background = "bisque2",font = "calibri 10 bold").place(x=10,y=40)
lbl_2 = ttk.Combobox(window,textvariable = txt_1, values = ["Yes","No"], background = "bisque2",font = "calibri 10 bold").place(x=275,y=40)
a1 = txt_1.get()
if a1 == "Yes":
txt_2=StringVar()
lbl_3 = Label(window,text = "Working directory path", background = "bisque2",font = "calibri 10 bold").place(x=10,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60).place(x=275,y=70)
txt_3=StringVar()
lbl_4 = Label(window,text = "file name (without extenstion)", background = "bisque2",font = "calibri 10 bold").place(x=10,y=100)
txt_c = Entry(window,textvariable=txt_2,width=60).place(x=275,y=100)
elif a1 == "No":
txt_2=StringVar()
lbl_3 = Label(window,text = "Working directory path", background = "bisque2",font = "calibri 10 bold").place(x=10,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60).place(x=275,y=70)
txt_3=StringVar()
lbl_4 = Label(window,text = "file1 name (without extenstion)", background = "bisque2",font = "calibri 10 bold").place(x=10,y=100)
txt_c = Entry(window,textvariable=txt_2,width=60).place(x=275,y=100)
txt_4=StringVar()
lbl_5 = Label(window,text = "file2 name (without extenstion)", background = "bisque2",font = "calibri 10 bold").place(x=10,y=130)
txt_d = Entry(window,textvariable=txt_2,width=60).place(x=275,y=130)
btn_1 = Button(window, text = "run",style = 'W.TButton',command=clicked)
btn_1.place(x=300,y=250)
window.configure(bg='bisque2')
window.resizable(0, 0)
window.mainloop()
def clicked():
a=1212
f_step()
У него есть поле со списком, но как только я выбираю один вариант (да или нет), он не обновляет следующие параметры. Пожалуйста, помогите мне решить эту проблему, так как я не знаю, как обновить приложение на основе входных данных в реальном времени. я не хочу, чтобы он обновлялся, как только я нажимаю кнопку. Также это только часть кода, с которой у меня возникла проблема, пожалуйста, сообщите.
то, что вы ищете, это lbl_2.bind("<<ComboboxSelected>>", f_step)
также обратите внимание, что вы должны добавить параметр в функцию f_step
, поскольку она передается из комбинированного виртуального события. Это обеспечит обновление всякий раз, когда параметр будет изменен.
Попробуй это:
from tkinter import *
from tkinter.ttk import *
import os
import time
import win32api
def f_step(event=None):
a1 = txt_1.get()
if a1 == "Yes":
txt_2=StringVar()
lbl_3 = Label(window,text = "Working directory path", background = "bisque2",font = "calibri 10 bold").place(x=10,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60).place(x=275,y=70)
txt_3=StringVar()
lbl_4 = Label(window,text = "file name (without extenstion)", background = "bisque2",font = "calibri 10 bold").place(x=10,y=100)
txt_c = Entry(window,textvariable=txt_2,width=60).place(x=275,y=100)
elif a1 == "No":
txt_2=StringVar()
lbl_3 = Label(window,text = "Working directory path", background = "bisque2",font = "calibri 10 bold").place(x=10,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60).place(x=275,y=70)
txt_3=StringVar()
lbl_4 = Label(window,text = "file1 name (without extenstion)", background = "bisque2",font = "calibri 10 bold").place(x=10,y=100)
txt_c = Entry(window,textvariable=txt_2,width=60).place(x=275,y=100)
txt_4=StringVar()
lbl_5 = Label(window,text = "file2 name (without extenstion)", background = "bisque2",font = "calibri 10 bold").place(x=10,y=130)
txt_d = Entry(window,textvariable=txt_2,width=60).place(x=275,y=130)
def clicked():
a=1212
#f_step()
window=Tk()
style = Style()
style.configure('W.TButton', font =
('calibri', 12, 'bold'),
foreground = 'blue')
s = Style() # Creating style element
s.configure('Wild.TRadiobutton', # First argument is the name of style. Needs to end with: .TRadiobutton
background='bisque2', # Setting background to our specified color above
font = "calibri 10 bold") # You can define colors like this also
window.title('Tool tool')
window.geometry("700x300+10+10")
#window.geometry(side = "top", fill = "both", expand = True)
txt_1=StringVar()
lbl_1 = Label(window,text = "Are result files same", background = "bisque2",font = "calibri 10 bold").place(x=10,y=40)
lbl_2 = Combobox(window,textvariable = txt_1, values = ["Yes","No"], background = "bisque2",font = "calibri 10 bold")
lbl_2.place(x=275,y=40)
#lbl_2.current(1)
lbl_2.bind("<<ComboboxSelected>>", f_step)
btn_1 = Button(window, text = "run",style = 'W.TButton',command=clicked)
btn_1.place(x=300,y=250)
window.configure(bg='bisque2')
window.resizable(0, 0)
window.mainloop()
также, если вы хотите обновлять только при нажатии кнопки запуска, вы можете вызвать f_step
из clicked()
и удалить привязку из поля со списком.
хорошо, согласно вашему запросу, вот обновленный код:
from tkinter import *
from tkinter.ttk import *
import os
import time
import win32api
def f_step(event=None):
global lbl_3
global txt_b
global lbl_4
global lbl_c
global lbl_5
global txt_d
hide()
a1 = txt_1.get()
txt_2=StringVar()
txt_3=StringVar()
lbl_3 = Label(window,text = "Working directory path", background = "bisque2",font = "calibri 10 bold")
lbl_3.place(x=10,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60)
txt_b.place(x=275,y=70)
txt_b = Entry(window,textvariable=txt_2,width=60)
txt_b.place(x=275,y=70)
lbl_4 = Label(window,text = "file name (without extenstion)", background = "bisque2",font = "calibri 10 bold")
lbl_4.place(x=10,y=100)
txt_c = Entry(window,textvariable=txt_2,width=60)
txt_c.place(x=275,y=100)
if a1 == "No":
lbl_5 = Label(window,text = "file2 name (without extenstion)", background = "bisque2",font = "calibri 10 bold")
lbl_5.place(x=10,y=130)
txt_d = Entry(window,textvariable=txt_2,width=60)
txt_d.place(x=275,y=130)
def hide():
#lbl_3.place_forget()
lbl_3.destroy()
txt_b.destroy()
lbl_4.destroy()
txt_c.destroy()
lbl_5.destroy()
txt_d.destroy()
def clicked():
a=1212
f_step()
window=Tk()
style = Style()
style.configure('W.TButton', font =
('calibri', 12, 'bold'),
foreground = 'blue')
s = Style() # Creating style element
s.configure('Wild.TRadiobutton', # First argument is the name of style. Needs to end with: .TRadiobutton
background='bisque2', # Setting background to our specified color above
font = "calibri 10 bold") # You can define colors like this also
window.title('Tool tool')
window.geometry("700x300+10+10")
lbl_3 = Label(window)
txt_b = Entry(window)
txt_b = Entry(window)
lbl_4 = Label(window)
txt_c = Entry(window)
lbl_5 = Label(window)
txt_d = Entry(window)
txt_1=StringVar()
lbl_1 = Label(window,text = "Are result files same", background = "bisque2",font = "calibri 10 bold").place(x=10,y=40)
lbl_2 = Combobox(window,textvariable = txt_1, values = ["Yes","No"], background = "bisque2",font = "calibri 10 bold")
lbl_2.place(x=275,y=40)
#lbl_2.current(1)
lbl_2.bind("<<ComboboxSelected>>", f_step)
btn_1 = Button(window, text = "run",style = 'W.TButton',command=clicked)
btn_1.place(x=300,y=250)
window.configure(bg='bisque2')
window.resizable(0, 0)
window.mainloop()
вы можете использовать widget.destroy()
, чтобы удалить виджет целиком, или widget.place_forget
, чтобы временно скрыть виджет. Примечание: если вы используете widget.place_forget
, вам не нужно заново создавать виджет, вместо этого измените существующий виджет, используя widget.config
Вы должны привязать виртуальное событие <<ComboboxSelected>>
к обратному вызову и показать необходимые метки и записи на основе выбора поля со списком в обратном вызове:
def f_step():
window = Tk()
window.title('Tool tool')
window.geometry("700x300+10+10")
#window.geometry(side = "top", fill = "both", expand = True)
window.configure(bg='bisque2')
window.resizable(0, 0)
s = ttk.Style() # Creating style element
s.configure('W.TButton', font=('calibri', 12, 'bold'), foreground='blue')
s.configure('Wild.TRadiobutton', # First argument is the name of style. Needs to end with: .TRadiobutton
background='bisque2', # Setting background to our specified color above
font = "calibri 10 bold") # You can define colors like this also
def on_change(event):
# show the labels and entries
lbl_3.place(x=10, y=70)
txt_b.place(x=275, y=70)
lbl_4.place(x=10, y=100)
txt_c.place(x=275, y=100)
a1 = txt_1.get()
if a1 == "Yes":
lbl_5.place_forget()
txt_d.place_forget()
else:
lbl_5.place(x=10, y=130)
txt_d.place(x=275, y=130)
txt_1 = StringVar()
Label(window, text = "Are result files same", background = "bisque2", font = "calibri 10 bold").place(x=10,y=40)
cb_1 = ttk.Combobox(window, textvariable=txt_1, values=["Yes","No"], background = "bisque2", font = "calibri 10 bold", state = "readonly")
cb_1.place(x=275,y=40)
cb_1.bind("<<ComboboxSelected>>", on_change)
# define the labels and entries and initially they are hidden
txt_2 = StringVar()
lbl_3 = Label(window, text = "Working directory path", background = "bisque2", font = "calibri 10 bold")
txt_b = Entry(window, textvariable=txt_2, width=60)
txt_3 = StringVar()
lbl_4 = Label(window, text = "file1 name (without extenstion)", background = "bisque2", font = "calibri 10 bold")
txt_c = Entry(window, textvariable=txt_3, width=60)
txt_4 = StringVar()
lbl_5 = Label(window, text = "file2 name (without extenstion)", background = "bisque2", font = "calibri 10 bold")
txt_d = Entry(window, textvariable=txt_4, width=60)
btn_1 = ttk.Button(window, text = "run", style='W.TButton', command=clicked)
btn_1.place(x=300, y=250)
window.mainloop()
Обратите внимание, что ваш код использует переменную txt_2
в записях txt_c
и txt_d
, и я думаю, что это опечатка, и исправьте ее.
Спасибо JacksonPro, все работает почти. Теперь, когда я выбираю «да или нет», он дает мне требуемые выходные данные, но проблема в том, что я меняю свой параметр с НЕТ на ДА, он не обновляет вывод (в моем случае он должен удалить «входная запись имени файла2» ). Мне понадобится эта модификация таким образом, чтобы весь виджет (другая часть инструмента, которая не показана в данном коде) автоматически настраивался после изменения параметров.