【发布时间】:2019-02-03 03:22:35
【问题描述】:
我试图在按下按钮时让文本出现在我的 GUI 应用程序的输入框中。目的是当一个按钮被按下时,一些定义的文本出现在教科书中,当另一个按钮被按下时,前一个输入框被清除,不同的文本被插入到同一个输入框中。
我是 Python 新手,因此不确定如何执行此操作?到目前为止,我已经获得了三个按钮来显示不同的文本,每个按钮在 GUI 中作为文本而不是在单独的文本框中显示文本。有人可以帮忙吗?这是我目前的代码:
`# ***** 前言代码 *****
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
def new():
tkinter.messagebox.showinfo('Window Title', 'Well, this is new...')
root = Tk()
root.title("GUI Test Version 2")
root.resizable(False, False)
root.geometry('{}x{}'.format(400, 400))
***** 主菜单 *****
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New Experiment...", command=new)
subMenu.add_command(label="New...", command=new)
subMenu.add_separator()
subMenu.add_command(label="Exit", command=root.destroy)
editMenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editMenu)
editMenu.add_command(label="Redo", command=new)
***** 工具栏 *****
toolbar = Frame(root, bg="light blue")
toolbar.pack(side=TOP, fill=X)
***** 创建按钮 *****
class App(object):
def __init__(self,root):
self.root = root
self.txt_frm = Frame(self.root, width=900, height=900)
self.txt_frm.pack(fill="both", expand=True)
button1 = Button(self.txt_frm,text="HELLO", command = self.hello_world)
button1.grid(column=0,row=2, padx=2, pady=2)
button2 = Button(self.txt_frm,text="GOODBYE", command = self.goodbye_world)
button2.grid(column=1,row=2, padx=2, pady=2)
button3 = Button(self.txt_frm,text="NEW", command = self.new_world, bg="red",fg="white")
button3.grid(column=2,row=2, padx=2, pady=2)
def hello_world(self):
label = Label(self.txt_frm,text='HELLO WORLD!')
label.grid(column=0,row=3)
def goodbye_world(self):
label = Label(self.txt_frm,text='GOODBYE WORLD!')
label.grid(column=1,row=3)
def new_world(self):
label = Label(self.txt_frm,text='THIS IS A NEW WORLD!')
label.grid(column=2,row=3)
***** 状态栏 *****
status = Label(root, text="Preparing to begin...", bd=1, relief=SUNKEN, anchor=W) # bd = bordered, relief = , appear placed in screen, anchor = w (NESW) needs two other properties
status.pack(side=BOTTOM, fill=X)
***** 运行代码 *****
app = App(root)
root.mainloop()`
【问题讨论】:
-
请不要在您的代码中穿插那些无用的标头。大多数人更喜欢的是我们可以复制和粘贴的单个代码块。另外,请尝试将代码缩减为minimal reproducible example。如果问题出在一个按钮和一个入口小部件上,我们真的只需要一个按钮和一个入口小部件来查看您在做什么(加上足够的代码使其运行)。
-
请提供一个代码,而不是制作标题。还修复缩进
-
你的代码有很多不相关的细节,比如菜单和标签,没有输入框。