繁体   English   中英

如何从Entry tkinter python获取变量值?

[英]How to get variable value from Entry tkinter python?

我正在尝试使用 tkinter 创建一个 GUI。 我能够使用按钮、标签等设置界面。但是,当我在界面中键入字符串或 int 时(使用 Entry,也使用组合框和 chekcbutton),如果尝试打印分配的变量,则不会出现,我只打印了以下内容而不是变量值:

.!entry, .!entry2, .!combobox, .!checkbutton

有人知道如何解决吗?

from tkinter import *
from tkinter.ttk import Combobox
from tkinter import filedialog

def browse_button1():
    global folder_path
    filename = filedialog.askdirectory()
    folder_path1.set(filename)
def browse_button2():
   global folder_path
   filename = filedialog.askdirectory()
   folder_path2.set(filename) 

main_window = Tk()
folder_path1 = StringVar()
folder_path2 = StringVar()
var = StringVar()
def1 = StringVar(main_window, value='Sharp')

# Labels
Label(main_window, text= "Folder Path").grid(row = 0, column = 0)
Label(main_window, text= "Scan File").grid(row = 1, column = 0)

#Text Input
e1 = Entry(main_window, width= 50, borderwidth= 5, textvariable= folder_path1)
e1.grid(row= 0, column= 1, columnspan= 2, sticky="we", pady=10)
e2 = Entry(main_window, width= 50, borderwidth= 5, textvariable= folder_path2)
e2.grid(row= 1, column= 1, columnspan= 2, sticky="we", pady=10)

#Combobox list
var.set("Sharp")
data = ("Sharp", "Intermediate", "Standard", "Soft")
cb = Combobox(main_window, values=data, textvariable= def1)
cb.grid(row=4, column= 1, sticky = 'w', pady=10)

#Checkbutton
cbu = Checkbutton(main_window)
cbu.grid(row=6, column=1, sticky = 'w', pady=10)

def on_click():
    print(f"{e1}, {e2}, {cb}, {cbu}")
    
#Buttons
Button(main_window, text= "Run", command = on_click, width = 25).grid(row= 8, column= 1, columnspan= 2, sticky="we", pady=10)
Button(main_window, text= "Browse", command = browse_button1, width = 12).grid(row= 0, column= 3)
Button(main_window, text= "Browse", command = browse_button2, width = 12).grid(row= 1, column= 3)

main_window.mainloop()

使用.get()方法检索小部件值。 简单地改变:

def on_click():
    print(f"{e1}, {e2}, {cb}, {cbu}")

至:

# create a variable to store the Checkbutton state
cb_var = StringVar()
# update 'cbu' to use that variable
cbu = Checkbutton(main_window, variable=cb_var)


def on_click():
    print(f"{e1.get()}, {e2.get()}, {cb.get()}, {cb_var.get()}")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM