簡體   English   中英

如何使用 tkinter 中的按鈕設置“Entry”小部件的文本/值/內容

[英]How to set the text/value/content of an `Entry` widget using a button in tkinter

我正在嘗試使用tkinter模塊使用 GUI 中的按鈕設置Entry小部件的文本。

這個 GUI 是為了幫助我將數千個單詞分為五類。 每個類別都有一個按鈕。 我希望使用按鈕會顯着加快我的速度,並且我想每次都仔細檢查單詞,否則我只會使用按鈕並讓 GUI 處理當前單詞並帶來下一個單詞。

出於某種原因,命令按鈕的行為不像我想要的那樣。 這是一個例子:

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()

到目前為止,當我能夠編譯時,單擊什么也不做。

您可能想使用insert方法。 你可以在這里找到 Tkinter Entry Widget 的文檔。

此腳本將文本插入到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()

如果您使用“文本變量” tk.StringVar() ,則只需set()即可。

無需使用條目刪除和插入。 此外,當條目被禁用或只讀時,這些功能不起作用! 但是,文本變量方法也可以在這些條件下工作。

import Tkinter as tk

...

entry_text = tk.StringVar()
entry = tk.Entry( master, textvariable=entry_text )
entry_text.set( "Hello World" )

您可以選擇以下兩種方法來設置Entry小部件的文本。 對於示例,假設導入的庫import tkinter as tk和根窗口root = tk.Tk()


  • 方法A:使用deleteinsert

    Widget Entry提供方法deleteinsert可用於將其文本設置為新值。 首先,您必須使用deleteEntry中刪除任何以前的舊文本,這些文本需要開始和結束刪除的位置。 由於我們要刪除完整的舊文本,因此我們從0開始,並在當前結束的任何地方結束。 我們可以通過END訪問該值。 之后Entry為空,我們可以在位置0插入new_text

     entry = tk.Entry(root) new_text = "Example text" entry.delete(0, tk.END) entry.insert(0, new_text)

  • 方法 B:使用StringVar

    您必須在示例中創建一個名為entry_text的新StringVar對象。 此外,您的Entry小部件必須使用關鍵字參數textvariable創建。 之后,每次使用set更改entry_text時,文本都會自動顯示在Entry小部件中。

     entry_text = tk.StringVar() entry = tk.Entry(root, textvariable=entry_text) new_text = "Example text" entry_text.set(new_text)

  • 完整的工作示例,其中包含通過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()

你的問題是當你這樣做時:

a = Button(win, text="plant", command=setText("plant"))

它試圖評估為命令設置的內容。 因此,在實例化Button對象時,它實際上調用了setText("plant") 這是錯誤的,因為您還不想調用 setText 方法。 然后它獲取此調用的返回值(即None ),並將其設置為按鈕的命令。 這就是為什么單擊按鈕什么都不做的原因,因為沒有為它設置命令。

如果您按照 Milan Skála 的建議進行操作並改用 lambda 表達式,那么您的代碼將起作用(假設您修復了縮進和括號)。

代替實際調用該函數的command=setText("plant") ,您可以設置command=lambda:setText("plant") ,它指定稍后將在您想調用該函數時調用該函數的內容。

如果你不喜歡 lambdas,另一種(稍微麻煩一點)的方法是定義一對函數來做你想做的事:

def set_to_plant():
    set_text("plant")
def set_to_animal():
    set_text("animal")

然后您可以使用command=set_to_plantcommand=set_to_animal - 這些將評估為相應的函數,但絕對command=set_to_plant()不同,后者當然會再次評估為None

一種方法是繼承一個新類EntryWithSet並定義使用Entry類對象的deleteinsert方法的set方法:

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()
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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM