首页 > 解决方案 > 如何让我的按钮知道输入框中的内容,然后在新窗口中打印该值?

问题描述

我想在你在输入框中写一些东西然后你按下按钮弹出一个新窗口并且在输入框中写的数字要在新窗口中打印为“你的身高是:”值“但之后许多尝试我仍然不明白如何去做。

我的代码:

import tkinter as tk
root = tk.Tk()
root.geometry("250x130")
root.resizable(False, False)

lbl = tk.Label(root, text="Input your height", font="Segoe, 11").place(x=8, y=52)
entry = tk.Entry(root,width=15).place(x=130, y=55)
btn1 = tk.Button(root, text="Enter", width=12, height=1).place(x=130, y=85) #command=entrytxt1

root.mainloop()

标签: pythonuser-interfacetkinter

解决方案


这就是我得到的:

import tkinter as tk

root = tk.Tk()
root.resizable(False, False)

def callback():
    # Create a new window
    new_window = tk.Toplevel()
    new_window.resizable(False, False)

    # `entry.get()` gets the user input
    new_window_lbl = tk.Label(new_window, text="You chose: "+entry.get())
    new_window_lbl.pack()

    # `new_window.destroy` destroys the new window
    new_window_btn = tk.Button(new_window, text="Close", command=new_window.destroy)
    new_window_btn.pack()

lbl = tk.Label(root, text="Input your height", font="Segoe, 11")
lbl.grid(row=1, column=1)

entry = tk.Entry(root, width=15)
entry.grid(row=1, column=2)

btn1 = tk.Button(root, text="Enter", command=callback)
btn1.grid(row=1, column=3)

root.mainloop()

基本上,当单击按钮时,它会调用名为callback. 它创建一个新窗口,获取用户的输入 ( entry.get()) 并将其放入标签中。


推荐阅读