[英]Get text from Tkinter entry search box with a button
我對 python 很陌生,我剛開始使用 Tkinter。 我正在嘗試制作一些自我練習文件。 到目前為止一切順利,但我遇到了一個問題(我將發布整個代碼,然后我將繼續解決這個問題,以便您可以看到我想要做什么以及我不明白該怎么做的地方)。
#!/usr/bin/python
from tkinter import *
from PIL import Image, ImageTk
import subprocess
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("ez-Installer")
self.pack(fill=BOTH, expand=1)
updateButton = Button(self, text="Update", command=self.system_update)
updateButton.place(x=50, y=50)
syncButton = Button(self, text="Sync packages", command=self.system_sync)
syncButton.place(x=150, y=50)
cmd1 = StringVar()
mEntry = Entry(self,textvariable=cmd1).pack()
installButton = Button(self, text="Install", command=self.system_install)
installButton.place(x=50, y=150)
def system_install(self):
package = cmd1.get()
install = "sudo pacman -S {} --noconfirm".format(package)
subprocess.call([install], shell=True)
def system_exit(self):
exit()
def system_update(self):
subprocess.call(["sudo pacman -Su --noconfirm"], shell=True)
def system_sync(self):
subprocess.call(["sudo pacman -Syy --noconfirm"], shell=True)
root = Tk()
root.geometry("400x300")
app = Window(root)
root.mainloop()
錯誤是在按下“安裝”按鈕時。 “cmd1 未定義”。
def system_install(self):
package = cmd1.get()
install = "sudo pacman -S {} --noconfirm".format(package)
subprocess.call([install], shell=True)
如您所見,我希望它從我在此處添加的搜索框條目中獲取文本:
cmd1 = StringVar()
mEntry = Entry(self,textvariable=cmd1).pack()
installButton = Button(self, text="Install", command=self.system_install)
installButton.place(x=50, y=150)
我知道我的條目在def init_window(self):
,但是如何從那里獲取cmd1
的值? 是否可以? 如果沒有或者太麻煩,類似的選擇是什么?
在您的system_install
方法中,您無法訪問cmd1
變量,因為您沒有將它附加到對象實例。 您剛剛在init_window
方法中將其創建為局部變量。 要解決這個問題, self.cmd1
在每個地方使用self.cmd1
使其成為一個實例變量,通過self
參數對所有方法可見。
一個單獨的問題是mEntry
將被定義為None
因為pack()
方法不返回任何內容。 我懷疑你的意思應該是:
self.cmd1 = StringVar()
self.mEntry = Entry(self,textvariable=self.cmd1)
self.mEntry.pack()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.