【问题标题】:Python: I'm trying to get TKinter to take a user input for a number after pressing a buttonPython:我试图让 TKinter 在按下按钮后接受用户输入的数字
【发布时间】:2023-01-14 20:47:54
【问题描述】:

我正在尝试获取它,以便在文本框中输入数字后,程序可以读取它并将其作为变量接收,稍后我可以将其用于公式,但我不确定我在做什么错了,所以我可以让它读取输入。

这是我目前所处的位置。

import tkinter as Tk
from tkinter import *
from itertools import cycle

window = Tk()
window.title("Title")
window.minsize(width=700, height=300)

canvas = Canvas(width=900, height=400)
canvas.create_image(50, 100)
canvas.grid(column=3,row=3)

TEXT = "MENU"

first_button_pressed = False


def second_ent():
  pass

def first_button_pressed():
  first_button.destroy()
  second_button.destroy()
  first_button_input = Entry()
  first_button_input.grid(column=2, row=1)
  label.config(text = "Enter a number.")
  first_ent_button = Button(window, text="Enter", command=first_ent)
  first_ent_button.grid(column=2, row=2)

def first_ent():
  number_entered = int(first_button_input.textinput("1.0", "end-1c"))
  print(number_entered)  

def second_button_pressed():
  phys_button.destroy()
  mag_button.destroy()
  MAG_input = Entry()
  MAG_input.grid(column=2, row=1)
  label.config(text = "Enter the Yo-Kai's Spirit stat!")
  mag_ent_button = Button(window, text="Enter", command=mag_ent)
  mag_ent_button.grid(column=2, row=2)


label = Label(text=TEXT)
label.grid(column=2, row=0)
first_button = Button(window, text="first button", command=first_button_pressed)
first_button.grid(column=2, row=1)
second_button = Button(window, text="second button", command=second_button_pressed)
second_button.grid(column=2, row=2)

window.mainloop()

我四处寻找其他解决方案,说要使用 .get() 但它似乎不起作用。

【问题讨论】:

  • 您的 Entry() 变量是局部变量,因此如果您在函数外部使用它,请确保首先在函数内部使用 global first_button_input 将变量全局化
  • 我接受了你的建议并尝试了,但我似乎遇到了语法错误。

标签: python user-interface tkinter button tkinter-entry


【解决方案1】:

这对于第 33 行的输入来说是不好的做法。

改变这个”

number_entered = int(first_button_input.textinput("1.0", "end-1c"))

到:

number_entered = int(first_button_input.get())

还要注释掉第 26 行 #first_button_input = Entry(window) 并将其放到第 45 行。因此您无需声明全局。

点击第一个按钮后的输出:

您将在调试中看到打印。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-05
    • 2021-02-09
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多