python-3.x 如何在Tkinter中根据组合框选择值(列表框)动态显示标签(文本)值?

vlf7wbxs  于 2023-01-03  发布在  Python
关注(0)|答案(1)|浏览(161)

我是新的tkinter应用程序。下面的代码工作正常。请帮助如何实现提到的功能。
1.动态值应显示在清除按钮上方或组合框下方(已用试剂包在底部)-现在有效
1.选择组合框时清除标签值。

import tkinter as tk
 from tkinter import ttk
 from tkinter import *
 from datetime import datetime
 # root window
 root = tk.Tk()
 root.geometry("500x350")
 root.resizable(False, False)
 root.title('Test')
 # Log Generator in frame
 Generator = tk.Frame(root)
 Generator.pack(padx=10, pady=10, fill='x', expand=True)

 def clear():
     combo.set('')

 # Function to print the index of selected option
 # in Combobox
 def get_log_file_name(*arg):
     date_Value = datetime.now().strftime("%Y_%m_%d_%I%M%S")
     output_file_name_value = "Log_"+date_Value
     if var.get() == "apple":
             Label(Generator, text="The value at index: "+output_file_name_value+".txt", font=('Helvetica 12')).pack()
     else:
             Label(Generator, text="The value at index: "+output_file_name_value+".html", font=('Helvetica 12')).pack()

 # Define Tuple of months
 months = ('apple','banana')

 # Create a Combobox widget

 label = ttk.Label(Generator, text="Selection_Option:",font=('Helvetica', 10, 'bold'))
 label.pack(fill='x', expand=True)
 var = StringVar()
 combo = ttk.Combobox(Generator, textvariable=var)
 combo['values'] = months
 combo['state'] = 'readonly'
 combo.pack(padx=5, pady=5)

 # Set the tracing for the given variable
 var.trace('w', get_log_file_name)

 # Create a button to clear the selected combobox 
 # text value
 button = Button(Generator, text="Clear", command=clear)
 button.pack(side=left)

 # Make infinite loop for displaying app on 
 # the screen
 Generator.mainloop()

bqucvtff

bqucvtff1#

在选择组合框时清除标签值。您需要捕获ComboboxSelect事件来完成此操作,并且如果捕获了函数,则要执行的函数应该如下所示

def comboboxEventCapture(e=None):
    label.configure(text='')
    # Your code after resetting variables!

下面是事件捕获部分

combo.bind("<<ComboboxSelect>>", comboboxEventCapture)

你可以随意命名函数,注意参数e是必需的,因为如果事件被捕获,事件本身就作为参数传递给函数,这在这里没有用(除非你要用它做些什么,否则就用e.objname)

相关问题