【问题标题】:Get text from Tkinter entry search box with a button使用按钮从 Tkinter 条目搜索框中获取文本
【发布时间】:2016-10-15 14:40:38
【问题描述】:

我对 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 的值?是否可以?如果不是,或者如果太麻烦,类似的替代方案是什么?

【问题讨论】:

    标签: python tkinter box tkinter-entry


    【解决方案1】:

    在您的system_install 方法中,您无法访问cmd1 变量,因为您没有将它附加到对象实例。您刚刚在 init_window 方法中将其创建为局部变量。要解决此问题,请在每个位置使用 self.cmd1 使其成为实例变量,通过 self 参数对所有方法都可见。

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

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

    【讨论】:

    • 是的。非常感谢你。在我写完之后,我真的意识到我真正想要的是什么,我用谷歌搜索并尝试了更多的东西。 cmd1 是 init_window 的局部变量,函数 system_install 无法知道它。您的解决方案有效 addinf self.到 system_install 中的 cmd1 和 mEntry 和 self.cmd1。谢谢你的课!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 2014-09-07
    相关资源
    最近更新 更多