python-3.x Tkinter,我怎样才能在def里面得到一个变量呢?

rbl8hiat  于 2023-02-20  发布在  Python
关注(0)|答案(1)|浏览(150)

我试图在def中获取变量"user_get"(user_input)

import tkinter as tk
from tkinter import ttk

window = tk.Tk()

#put settings in place (username input)
window.geometry('1920x1080')
window.configure(bg = 'blue')

def entered(user_input):
    user_get = user_input.widget.get()
    user_input.widget.delete(0, 'end')
    print(user_get)
    return user_get
    user_input.widget.destroy()


# TextBox (input)
user_input = tk.Entry(window)
user_input.pack()
user_input.place(x = 100,y = 40)
user_input.bind("<Return>", entered) 


thing = user_get
print(thing)

window.mainloop()

我试过:

  • return(我不是很理解)
aiazj4mn

aiazj4mn1#

在这里,我设置了user_input变量在全局作用域中可用,entered函数中的global关键字允许该函数修改全局变量,现在,当您键入条目并点击Return时,user_input的值将被更新。
我定义了一个示例函数,每当按下一个按钮时,它都会打印这个值。注意,在您向Entry添加文本并按下Return之前,将打印一个空字符串!
同样,在root.mainloop()之前执行的任何类似print(user_input)的调用都将打印空字符串,因为user_input的值还没有更新。

import tkinter as tk

def entered(_event):
    global user_input  # allow this function to modify this variable
    user_input = entry.get()  # update the variable with the entry text
    entry.delete(0, 'end')  # clear entry contents

def use_value_from_entry():
    """Example function to use the value stored in 'user_input'"""
    print(user_input)
    

window = tk.Tk()

user_input = ''  # create a variable to store user input in the global scope
entry = tk.Entry(window)  # create the entry widget
entry.pack()  # add the widget to the UI
entry.bind('<Return>', entered)  # bind the event handler

# this button runs an example function to get the current value of 'user_input'
button = tk.Button(window, text='Click Me', command=use_value_from_entry)
button.pack()

window.mainloop()  # run the app

#Stockmage updated this

相关问题