如何制作tkinter条目小部件?

时间:2013-06-01 21:56:55

标签: python python-3.x tkinter data-entry

这是我的代码:

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条目小部件出现在与文本相同的窗口中。有人可以告诉我该怎么做?

2 个答案:

答案 0 :(得分: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

对我来说很好。

答案 1 :(得分:0)

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

这是在tkinter中执行此操作的最简单方法。如果你需要别的东西请问我:)