2015-03-03 46 views
0

我試圖做一個程序中的按鈕的選擇, 進行到下一個程序,使用Tkinter(窗口中的python 2.7)。 我一直在谷歌運氣沒有運氣。我可能是 缺乏正確的術語和流行語。無論如何,我希望問題是清楚的。謝謝。從一個文件攜帶選擇到下一個

讓我試試並演示如下: ...所以我們有兩個文件:PROGRAM_1.py和PROGRAM_2.py他們將在單獨的文件。

PROGRAM_1.py

from Tkinter import * 
import os 
import Tkinter as tk 

start_color = ["blue", "red"] 
root = Tk() 
root.title("please choose a starting color") 
# Set background # 
root.configure(background="green") 
root.geometry("600x150") 
# Buttons # 
topFrame = Frame(root) 
topFrame.pack() 
bottomFrame = Frame(root) 
bottomFrame.pack(side=LEFT) 

start_color[0] = Button(topFrame, text="Choose Blue", fg="black",  bg="white", font='bold') 
start_color[1] = Button(topFrame, text="Choose Red", fg="black", bg="white",  font='bold') 

start_color[0].pack(side=LEFT) 
start_color[1].pack(side=LEFT) 

def blue(event): 
    print "u chose the blue" 
    os.system("PROGRAM_2.py") 
    # then exit and startup PROGRAM_2".py 
start_color[0].bind("<Button-1>", blue) 

def red(event): 
    print "u chose the red" 
    os.system("PROGRAM_2.py") 
    # then exit and startup PROGRAM_2".py 
start_color[1].bind("<Button-1>", red) 

root.mainloop() 

PROGRAM_2.py

from Tkinter import * 
import os 
import Tkinter as tk 

start_color = ["blue", "red"] 

root = Tk() 

print "your color is" 
print start_color["......."] # <--- And then the choice from PROGRAM_1.py 

root.mainloop() 

回答

1

傳遞的選擇PROGRAM_2.PY作爲命令行參數。您可以使用sys.argv列表訪問PROGRAM_2.PY中的命令行參數。

import sys 

if len(sys.argv > 1): 
    start_color = sys.argv[1] 
. 
. 
. 
print "your color is", start_color 

而且在PROGRAM_1.PY:那麼,在PROGRAM2.PY進口sys與替換線start_color = ["blue", "red"]

def blue(event): 
    print "u chose the blue" 
    os.system("python PROGRAM_2.py blue") 
    # then exit and startup PROGRAM_2".py 

def red(event): 
    print "u chose the red" 
    os.system("python PROGRAM_2.py red") 
    # then exit and startup PROGRAM_2".py 

值得指出的是,os.system()不退出當前程序;它將給定的命令作爲新進程運行並等待它終止。

+0

謝謝。我會放棄它。 – ToFo 2015-03-03 13:01:44

+0

我無法完成這項工作。讓我告訴你我做了什麼。首先,您要刪除PROGRAM_1.py中的按鈕 - 所以我再次添加它們 – ToFo 2015-03-03 13:32:35

+0

不,我沒有刪除按鈕 - 只是將調用替換爲'os.system()'來傳遞命令行參數。 – mhawke 2015-03-03 13:35:31

-1
from Tkinter import * 
import os 
import Tkinter as tk 
import sys 

root = Tk() 


if (len(sys.argv) > 1): 
    start_color = sys.argv[1] 

print "your color is", start_color 

root.mainloop() 
+0

只需一個小的語法修正符合:if(len(sys.argv)> 1): – ToFo 2015-03-03 14:57:09