如何使用 tkinter 中的按钮设置“Entry"小部件的文本/值/内容 [英] How to set the text/value/content of an `Entry` widget using a button in tkinter

查看:31
本文介绍了如何使用 tkinter 中的按钮设置“Entry"小部件的文本/值/内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆