【问题标题】:Python (Tkinter) Click button to make text appear in entry box?Python(Tkinter)单击按钮使文本出现在输入框中?
【发布时间】: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。如果问题出在一个按钮和一个入口小部件上,我们真的只需要一个按钮和一个入口小部件来查看您在做什么(加上足够的代码使其运行)。
  • 请提供一个代码,而不是制作标题。还修复缩进
  • 你的代码有很多不相关的细节,比如菜单和标签,没有输入框。

标签: python button tkinter


【解决方案1】:

读取和写入条目的常用方法是使用 StringVar 作为文本变量。检查下面的代码:

from tkinter import *

root = Tk()
root.geometry('300x100')

class App(object):
     def __init__(self,root):
         self.root = root
         self.txt_frm = Frame(self.root, width=900, height=900, bg='khaki')
         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)
         self.entry_var = StringVar()
         entry = Entry(self.txt_frm, textvariable=self.entry_var)
         entry.grid(column=0, row=3, columnspan=2, padx=2, pady=2)

     def hello_world(self):
            self.entry_var.set('Hello')

     def goodbye_world(self):
            self.entry_var.set('World')

app = App(root)
root.mainloop()

我将 StringVar self.entry_var 分配给条目。然后我使用按钮回调函数通过修改self.entry_var来改变条目的内容。

【讨论】:

    【解决方案2】:

    __init__ 中创建一个标签,稍后使用label.config(text=text) 更改其文本。这是一个示例代码:

    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)
            self.label = Label(self.txt_frm,text='')
            self.label.grid(column=0,row=3)
        def hello_world(self):
            self.label.config(text="HELLO WORLD!")
    
        def goodbye_world(self):
            self.label.config(text="GOODBYE WORLD!")
    
        def new_world(self):
            self.label.config(text="THIS IS A NEW WORLD!")
    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()
    

    【讨论】:

    • 这真的很有帮助并回答了我的问题。我也不确定如何保存这些条目的内容。例如,您通常会在文本编辑器应用程序中使用保存对话框将框添加到文本文件中?请问你能帮忙吗?
    • 目前保存的代码是: def save_file(): savefile = open ("newfile.txt", "w") savefile.write("Entry Box 1: " + entry_box1.get ()) savefile.write("\n输入框 2: " + entry_box2.get()) savefile.write("\n输入框 3: " + entry_box3.get()) savefile.close ()
    • 但是这并没有显示保存对话框。当我重新运行代码时,旧文件被覆盖,我需要能够为每个文件指定一个文件名,并让它们与条目框中的文本分别保存。我该怎么做?
    • @HenryPowell-Davies,我在您的代码中看不到任何条目。你能告诉我你在说哪个条目吗?但是,如果您想获取标签的文本,请使用self.label["text"],它会将文本作为字符串返回给您
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多