python - 使用按钮从 Tkinter 条目搜索框中获取文本

标签 python tkinter box tkinter-entry

我对 python 还很陌生,刚刚开始使用 Tkinter。我正在尝试制作一些 self 练习文件。到目前为止一切顺利,但我遇到了一个问题(我将发布整个代码,之后我将继续解决问题,以便您可以看到我想要做什么以及我不明白该怎么做)。

#!/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 参数对所有方法可见的实例变量。

另一个问题是 mEntry 将被定义为 None,因为 pack() 方法不返回任何内容。我怀疑你的意思应该是:

self.cmd1 = StringVar()
self.mEntry = Entry(self,textvariable=self.cmd1)
self.mEntry.pack()

关于python - 使用按钮从 Tkinter 条目搜索框中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40060383/

相关文章:

python - 我的函数对是否需要第二个参数感到困惑(python,matplotlib)

node.js - Box Api - 如何获取评论文件的用户详细信息

python - 在哪里可以找到 box python SDK 的 jwt_key_id

ios - box-ios-preview-sdk : Memory leak in pspdfkit

python - 在 pandas 或 numpy 中,我们可以在行上设置一个标志来进行向量化并将其用于下一行计算

python - 使用 Python 创建终端程序

Python、Cv2、numpy 来指示图片/图像中的区域

python - 使用 gletools 和教程代码时出现 GL_TEXTURE_2D_ARRAY 错误

python - 如何为 ttk.Entry 小部件注册 @staticmethod 密码检查器回调?

python - 如何创建带有图像和文本的复选按钮?