2013-06-01 45 views
1

這是我的代碼:如何製作tkinter入口小部件?

import random 
from tkinter import * 
root=Tk() 
a=Canvas(root, width=1000, height=1000) 
a.pack() 
e = Entry(root) 
paralist = [] 
x=random.randint(1,10) 
file = open("groupproject.txt") 
line = file.readline() 
for line in file: 
    paralist.append(line.replace("\n", "")); 

a.create_text(500,50, text = "Typing Fun", width = 700, font = "Verdana", fill = "purple") 
a.create_text(500,300, text = paralist[x], width = 700, font = "Times", fill = "purple") 

#master = Tk() 
#a = Entry(master) 
#a.pack() 
#a.focus_set() 
#def callback(): 
# print (a.get()) 


root.mainloop() 

註釋的部分應該是打印一個段落下方的輸入小工具,而是它提供了一個錯誤IndexError: list index out of range線路a.create_text(500,300, text = paralist[x], width = 700, font = "Times", fill = "purple")。如果我使用e而不是a,但它可以在單獨的窗口中打開條目窗口小部件。

我試圖讓tkinter入口小部件與文本出現在同一個窗口中。有人可以告訴我如何做到這一點?

+0

你聲明'root = Tk()',然後'master = Tk()',然後將你的條目放在'master'而不是'root'內。 – Evilunclebill

回答

2

首先,

paralist = [] 列表是空的,所以1到10之間的隨機字將是自列表那裏有什麼不妥。

master = Tk() # since Tk() is already assigned to root this will make a new window 
a = Entry(master) # a is already assigned to canvas 
a.pack() # this is already declare under a=canvas 
a.focus_set() 
def callback(): 
    print (a.get()) 

編輯:

我懷疑你的文件可能是問題所在。此代碼:

import random 
from tkinter import * 

root = Tk() 

a = Canvas(root, width = 400, height = 400) 
a.pack() 
e = Entry(root) 
e.pack() 

paralist = [] 

x = random.randint(1,10) 

file = open("teste.txt") 
line = file.readline() 

for line in file: 
    paralist.append(line.replace("\n", "")); 

a.create_text(200,50, text = "Typing Fun", width = 700, font = "Verdana", fill = "purple") 
a.create_text(200,300, text = paralist[x], width = 700, font = "Times", fill = "purple") 

b = Entry(root) 
b.pack() 
b.focus_set() 

def callback(): 
    print (a.get()) 

root.mainloop() 

以此爲 「teste.txt」:

test0 
test1 
test2 
test3 
test4 
test5 
test6 
test7 
test8 
test9 
test10 

工作正常。

+0

實際上,我的程序將文件中的行添加到for循環的列表中。那麼,我該如何去解決這個問題,用root替換master,並且用e給我索引錯誤... soooo任何幫助將不勝感激:) – zara

+0

檢查我的編輯,添加了一個工作示例。 – Evilunclebill

0
import tkinter 
window = tkinter. Tk() 
window.geometry('200x200') 
ent= tkinter.Entry(window) 
ent.pack() 

這是在tkinter中最簡單的方法。如果你需要別的東西只要問我:)

相關問題