如何在tkinter中使用按钮设置`Entry`小部件的文本/值/内容 [英] How to set the text/value/content of an `Entry` widget using a button in tkinter
问题描述
我正在尝试使用tkinter
模块在GUI中使用按钮设置Entry
小部件的文本.
I am trying to set the text of an Entry
widget using a button in a GUI using the tkinter
module.
此GUI可以帮助我将数千个单词分为五个类别.每个类别都有一个按钮.我希望使用按钮可以大大提高我的速度,并且我想每次都仔细检查单词,否则我将只使用该按钮并让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.
由于某些原因,命令按钮的行为不如我希望的那样.这是一个例子:
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.
推荐答案
您可能想使用 insert
方法. 您可以在此处找到Tkinter Entry Widget的文档.
此脚本将文本插入Entry
.可以在Button的command
参数中更改插入的文本.
This script inserts a text into Entry
. The inserted text can be changed in command
parameter of the Button.
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()
这篇关于如何在tkinter中使用按钮设置`Entry`小部件的文本/值/内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!