1

This is my code:

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()

The commented section is supposed to print an entry widget underneath a paragraph but instead it gives an error IndexError: list index out of range for line a.create_text(500,300, text = paralist[x], width = 700, font = "Times", fill = "purple"). If I use e instead of a it works but opens the entry widget in a separate window.

I'm trying to make the tkinter entry widget appear in the same window as the text. Can someone please tell me how to do this?

vidit
  • 6,293
  • 3
  • 32
  • 50
zara
  • 375
  • 1
  • 4
  • 18
  • You are declaring `root=Tk()` and then afterwards `master = Tk()` and then place your entry inside `master` instead of `root`. – Evilunclebill Jun 01 '13 at 22:00

2 Answers2

2

First off,

paralist = [] The list is empty so a random word between 1 and 10 will be wrong since theres nothing in the list.

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())

Edit:

I suspect that your file might be the problem. This code:

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()

With this as "teste.txt":

test0
test1
test2
test3
test4
test5
test6
test7
test8
test9
test10

Works fine for me.

Evilunclebill
  • 769
  • 3
  • 9
  • 27
  • Actually my program appends lines from the file into the list in the for loop. So how do I go about fixing this, replacing master with root and a with e gives me the Index error...soooo any help would be appreciated :) – zara Jun 01 '13 at 22:43
0
import tkinter
window = tkinter. Tk()
window.geometry('200x200')
ent= tkinter.Entry(window)
ent.pack()

This is the easiest way to do it in tkinter. If you need something else Just ask me:)

Jordanian
  • 25
  • 10