【问题标题】:how to give the value selected from menu button as input to os.system in python gui如何将从菜单按钮中选择的值作为输入到python gui中的os.system
【发布时间】:2015-07-01 01:07:45
【问题描述】:

下面的 python gui 代码我试图从下拉菜单按钮(图形和密度)中选择值,并尝试将它们作为命令行参数传递给 readfile() 函数中的 os.system 命令,如下所示,但是我在将我从下拉菜单中选择的值传递给 os.system 命令时遇到问题。

导入操作系统 将 Tkinter 导入为 tk

def buttonClicked(btn):
    density= btn 

def graphselected(graphbtn):
    graph=graphbtn

def readfile():
    os.system( 'python C:Desktop/python/ABC.py graph density')

root = tk.Tk()
root.title("Dense Module Enumeration")

btnList=[0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
btnMenu = tk.Menubutton(root, text='Density')
contentMenu = tk.Menu(btnMenu)
btnMenu.config(menu=contentMenu)

for btn in btnList:
    contentMenu.add_command(label=btn, command = lambda btn=btn: buttonClicked(btn))
btnMenu.pack()


graph_list=['graph1.txt','graph2.txt','graph3.txt','graph.txt']
btnMenu = tk.Menubutton(root, text='graph')
contentMenu = tk.Menu(btnMenu)
btnMenu.config(menu=contentMenu)

for btn in graph_list:
    contentMenu.add_command(label=btn, command =lambda btn= btn: graphselected(btn))
btnMenu.pack()

button = tk.Button(root, text="DME", command=readfile)

button.pack()    
root.mainloop()

【问题讨论】:

    标签: python python-2.7 tkinter subprocess


    【解决方案1】:

    使用functools.partial 很容易实现 - 为每个按钮的功能应用所需的值。这是一个示例:

    from functools import partial
    import Tkinter as tk
    
    BTNLIST = [0.0, 0.1, 0.2]
    
    def btn_clicked(payload=None):
        """Just prints out given payload."""
        print('Me was clicked. Payload: {}'.format(payload))
    
    
    def init_controls():
        """Prepares GUI controls and starts mainloop"""
        root = tk.Tk()
        menu = tk.Menu(root)
        root.config(menu=menu)
        sample_menu = tk.Menu(menu)
        menu.add_cascade(label="Destiny", menu=sample_menu)
        for btn_value in BTNLIST:
            sample_menu.add_command(
                label=btn_value,
                # Here is the trick with partial
                command=partial(btn_clicked, btn_value)
            )
        root.mainloop()
    
    
    init_controls()
    

    【讨论】:

      【解决方案2】:

      按照您的方式,graphdensitygraphselected()buttonClicked() 的局部变量。因此,readfile() 永远无法访问这些变量,除非您在所有三个函数中将它们声明为全局变量。

      然后您想格式化一个字符串以合并graphdensity 中的值。您可以使用字符串 .format method 来做到这一点。

      结合你的三个功能变成

      def buttonClicked(btn):
          global density
          density = btn 
      
      def graphselected(graphbtn):
          global graph
          graph = graphbtn
      
      def readfile():
          global density, graph
          os.system('python C:Desktop/python/ABC.py {} {}'.format(graph, density))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-12
        • 1970-01-01
        • 2016-06-10
        • 1970-01-01
        • 1970-01-01
        • 2014-08-11
        • 2013-08-18
        • 2021-04-07
        相关资源
        最近更新 更多