2014-09-02 66 views
1

我試圖在tkinter中編寫一個應用程序,該應用程序將從您從下拉菜單中選擇的文件加載隨機行,並在文本窗口中顯示選定的行。tkinter變量下拉選擇空

好像在insert_text變量「VAR」不返回所選擇的「選項」,但造成了下面的錯誤,而「空」字符串:

"File not found error" (FileNotFoundError: [Errno2] No such file or directory: '').

請幫幫忙!

#!/usr/bin/env python 
# Python 3 

import tkinter 
from tkinter import ttk 
import random 

class Application: 

    def __init__(self, root): 
     self.root = root 
     self.root.title('Random Stuff') 
     ttk.Frame(self.root, width=450, height=185).pack()  
     self.init_widgets() 
     var = tkinter.StringVar(root) 
     script = var.get() 
     choices = ['option1', 'option2', 'option3'] 
     option = tkinter.OptionMenu(root, var, *choices) 
     option.pack(side='right', padx=10, pady=10)    

    def init_widgets(self): 
     ttk.Button(self.root, command=self.insert_txt, text='Button', width='10').place(x=10, y=10) 
     self.txt = tkinter.Text(self.root, width='45', height='5') 
     self.txt.place(x=10, y=50) 

    def insert_txt(self): 
     var = tkinter.StringVar(root) 
     name = var.get() 
     line = random.choice(open(str(name)).readlines()) 
     self.txt.insert(tkinter.INSERT, line) 

if __name__ == '__main__': 
    root = tkinter.Tk() 
    Application(root) 
    root.mainloop() 
+0

感謝您編輯我的問題! :)我看到它看起來很奇怪,但是當我試圖編輯它時,就像我第一次輸入它一樣。 : -/ – moupy 2014-09-02 21:27:18

回答

2

那是因爲你只是創建一個空StringVar沒有被修改後,並返回一個空字符串。

OptionMenu採用command參數,每次選擇其他選項時都會調用指定的方法。現在,你可以這樣調用的方法,代替你insert_txt

def __init__(self): 
    # ... 
    self.var = tkinter.StringVar() 
    self.options = tkinter.OptionMenu(root, var, *choices, command=self.option_selected) 
    # ...  

def option_selected(self, event): 
    name = self.var.get() 
    # The stuff you already had 

此外,您必須清空Text小部件,否則以前的文本會留下來。我認爲Entry小部件也是更好的。

+0

非常感謝,這真的幫了我很多! :)))可悲的是,我不能贊成,因爲我似乎缺乏代表。 : - / – moupy 2014-09-02 21:19:44