Python 如何使用 tkinter 中的按钮设置“Entry”小部件的文本/值/内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16373887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the text/value/content of an `Entry` widget using a button in tkinter
提问by unlockme
I am trying to set the text of an Entrywidget using a button in a GUI using the tkintermodule.
我正在尝试Entry使用tkinter模块在 GUI 中使用按钮设置小部件的文本。
This GUI is to help me classify thousands of words into five categories. Each of the categories has a button. I was hoping that using a button would significantly speed me up and I want to double check the words every time otherwise I would just use the button and have the GUI process the current word and bring the next word.
这个 GUI 是帮助我将数千个单词分为五个类别。每个类别都有一个按钮。我希望使用按钮可以显着加快我的速度,我想每次都仔细检查单词,否则我只会使用按钮并让 GUI 处理当前单词并输入下一个单词。
The command buttons for some reason are not behaving like I want them to. This is an example:
出于某种原因,命令按钮的行为不像我希望的那样。这是一个例子:
import tkinter as tk
from tkinter import ttk
win = tk.Tk()
v = tk.StringVar()
def setText(word):
v.set(word)
a = ttk.Button(win, text="plant", command=setText("plant"))
a.pack()
b = ttk.Button(win, text="animal", command=setText("animal"))
b.pack()
c = ttk.Entry(win, textvariable=v)
c.pack()
win.mainloop()
So far, when I am able to compile, the click does nothing.
到目前为止,当我能够编译时,点击什么都不做。
采纳答案by Milan Skála
You might want to use insertmethod.
您可能想要使用insert方法。
This script inserts a text into Entry. The inserted text can be changed in commandparameter of the Button.
此脚本将文本插入到Entry. 插入的文本可以command在按钮的参数中更改。
from tkinter import *
def set_text(text):
e.delete(0,END)
e.insert(0,text)
return
win = Tk()
e = Entry(win,width=10)
e.pack()
b1 = Button(win,text="animal",command=lambda:set_text("animal"))
b1.pack()
b2 = Button(win,text="plant",command=lambda:set_text("plant"))
b2.pack()
win.mainloop()
回答by BuvinJ
If you use a "text variable" tk.StringVar(), you can just set()that.
如果您使用“文本变量” tk.StringVar(),则可以set()。
No need to use the Entry delete and insert. Moreover, those functions don't work when the Entry is disabled or readonly! The text variable method, however, does work under those conditions as well.
无需使用条目删除和插入。此外,当条目被禁用或只读时,这些功能不起作用!然而,文本变量方法也适用于这些条件。
import Tkinter as tk
...
entryText = tk.StringVar()
entry = tk.Entry( master, textvariable=entryText )
entryText.set( "Hello World" )
回答by Nae
One way would be to inherit a new class,EntryWithSet, and defining setmethod that makes use of deleteand insertmethods of the Entryclass objects:
一种方式是继承了一个新类EntryWithSet,并定义set方法是利用了delete与insert该方法的Entry类对象:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
class EntryWithSet(tk.Entry):
"""
A subclass to Entry that has a set method for setting its text to
a given string, much like a Variable class.
"""
def __init__(self, master, *args, **kwargs):
tk.Entry.__init__(self, master, *args, **kwargs)
def set(self, text_string):
"""
Sets the object's text to text_string.
"""
self.delete('0', 'end')
self.insert('0', text_string)
def on_button_click():
import random, string
rand_str = ''.join(random.choice(string.ascii_letters) for _ in range(19))
entry.set(rand_str)
if __name__ == '__main__':
root = tk.Tk()
entry = EntryWithSet(root)
entry.pack()
tk.Button(root, text="Set", command=on_button_click).pack()
tk.mainloop()
回答by user9913277
Your problem is that when you do this:
你的问题是,当你这样做时:
a = Button(win, text="plant", command=setText("plant"))
it tries to evaluate what to set for the command. So when instantiating the Buttonobject, it actually calls setText("plant"). This is wrong, because you don't want to call the setText method yet. Then it takes the return value of this call (which is None), and sets that to the command of the button. That's why clicking the button does nothing, because there is no command set for it.
它尝试评估要为命令设置的内容。所以在实例化Button对象时,它实际上调用了setText("plant"). 这是错误的,因为您还不想调用 setText 方法。然后它获取此调用的返回值(即None),并将其设置为按钮的命令。这就是为什么点击按钮什么都不做,因为没有为它设置命令。
If you do as Milan Skála suggested and use a lambda expression instead, then your code will work (assuming you fix the indentation and the parentheses).
如果您按照 Milan Skála 的建议进行操作并改用 lambda 表达式,那么您的代码将起作用(假设您修复了缩进和括号)。
Instead of command=setText("plant"), which actually callsthe function, you can set command=lambda:setText("plant")which specifies something which will call the function later, when you want to call it.
您可以设置which 指定稍后将调用该函数的内容command=setText("plant"),而不是实际调用该函数的command=lambda:setText("plant"), 当您想要调用它时。
If you don't like lambdas, another (slightly more cumbersome) way would be to define a pair of functions to do what you want:
如果您不喜欢 lambda,另一种(稍微麻烦一点)的方法是定义一对函数来执行您想要的操作:
def set_to_plant():
set_text("plant")
def set_to_animal():
set_text("animal")
and then you can use command=set_to_plantand command=set_to_animal- these will evaluate to the corresponding functions, but are definitely notthe same as command=set_to_plant()which would of course evaluate to Noneagain.
然后你可以使用command=set_to_plant和command=set_to_animal-这些将评估到相应的功能,但绝对不一样command=set_to_plant()这当然会评估为None一次。
回答by finefoot
You can choose between the following two methods to set the text of an Entrywidget. For the examples, assume imported library import tkinter as tkand root window root = tk.Tk().
您可以选择以下两种方法来设置Entry小部件的文本。对于示例,假设导入的 libraryimport tkinter as tk和 root window root = tk.Tk()。
Method A: Use
deleteandinsertWidget
Entryprovides methodsdeleteandinsertwhich can be used to set its text to a new value. First, you'll have to remove any former, old text fromEntrywithdeletewhich needs the positions where to start and end the deletion. Since we want to remove the full old text, we start at0and end at wherever the end currently is. We can access that value viaEND. Afterwards theEntryis empty and we can insertnew_textat position0.entry = tk.Entry(root) new_text = "Example text" entry.delete(0, tk.END) entry.insert(0, new_text)
方法 A:使用
delete和insert插件
Entry提供的方法delete和insert可用于给它的文本设置为一个新值。首先,你必须删除任何前,旧文本从Entry与delete该需要的位置在哪里开始和结束删除。由于我们要删除完整的旧文本,因此我们从0当前结束的位置开始并结束。我们可以通过访问该值END。之后Entry是空的,我们可以new_text在位置插入0。entry = tk.Entry(root) new_text = "Example text" entry.delete(0, tk.END) entry.insert(0, new_text)
Method B: Use
StringVarYou have to create a new
StringVarobject calledentry_textin the example. Also, yourEntrywidget has to be created with keyword argumenttextvariable. Afterwards, every time you changeentry_textwithset, the text will automatically show up in theEntrywidget.entry_text = tk.StringVar() entry = tk.Entry(root, textvariable=entry_text) new_text = "Example text" entry_text.set(new_text)
方法 B:使用
StringVar您必须创建一个在示例中
StringVar调用的新对象entry_text。此外,您的Entry小部件必须使用关键字参数创建textvariable。之后,每次使用 更改entry_text时set,文本都会自动显示在Entry小部件中。entry_text = tk.StringVar() entry = tk.Entry(root, textvariable=entry_text) new_text = "Example text" entry_text.set(new_text)
Complete working example which contains both methods to set the text via
Button:This window
is generated by the following complete working example:
import tkinter as tk def button_1_click(): # define new text (you can modify this to your needs!) new_text = "Button 1 clicked!" # delete content from position 0 to end entry.delete(0, tk.END) # insert new_text at position 0 entry.insert(0, new_text) def button_2_click(): # define new text (you can modify this to your needs!) new_text = "Button 2 clicked!" # set connected text variable to new_text entry_text.set(new_text) root = tk.Tk() entry_text = tk.StringVar() entry = tk.Entry(root, textvariable=entry_text) button_1 = tk.Button(root, text="Button 1", command=button_1_click) button_2 = tk.Button(root, text="Button 2", command=button_2_click) entry.pack(side=tk.TOP) button_1.pack(side=tk.LEFT) button_2.pack(side=tk.LEFT) root.mainloop()
完整的工作示例,其中包含通过
Button以下两种方法设置文本:这个窗口
由以下完整的工作示例生成:
import tkinter as tk def button_1_click(): # define new text (you can modify this to your needs!) new_text = "Button 1 clicked!" # delete content from position 0 to end entry.delete(0, tk.END) # insert new_text at position 0 entry.insert(0, new_text) def button_2_click(): # define new text (you can modify this to your needs!) new_text = "Button 2 clicked!" # set connected text variable to new_text entry_text.set(new_text) root = tk.Tk() entry_text = tk.StringVar() entry = tk.Entry(root, textvariable=entry_text) button_1 = tk.Button(root, text="Button 1", command=button_1_click) button_2 = tk.Button(root, text="Button 2", command=button_2_click) entry.pack(side=tk.TOP) button_1.pack(side=tk.LEFT) button_2.pack(side=tk.LEFT) root.mainloop()
回答by Kishore Sharma
e= StringVar()
def fileDialog():
filename = filedialog.askopenfilename(initialdir = "/",title = "Select A
File",filetype = (("jpeg","*.jpg"),("png","*.png"),("All Files","*.*")))
e.set(filename)
la = Entry(self,textvariable = e,width = 30).place(x=230,y=330)
butt=Button(self,text="Browse",width=7,command=fileDialog).place(x=430,y=328)


