I have a long chunk of code. I do not want to paste it all here, so let me explain what I am trying to accomplish here. Based on a number provided by the user I want to create that many text boxes and then get what is entered into that text box and insert that into the dictionary. I have tried this a few ways and just cannot get it to work correctly. The list is either empty or it only contains the last text box as the value for each key.
def multiple_choice():
def add():
top.destroy()
top = Tk()
top.title("Add Question")
w = 800
h = 800
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
question = Label(top, text="Question to be asked?", font = "Times 14 bold", fg = "blue")
question.grid(row = 2, column = 4)
questionText = Text(top, borderwidth = 5, width=50,height=5, wrap=WORD, background = 'grey')
questionText.grid(row = 3, column = 4)
numQuestions = Label(top, text = "Number of answer choices?", font = "Times 14 bold", fg = "blue")
numQuestions.grid(row = 4, column=4)
num = Entry(top, bd = 5)
num.grid(row=5, column = 4)
answerList = {}
def multiple():
def preview():
preview = Tk()
top.title("Question Preview")
w = 500
h = 500
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
title = Label(preview, text = "Short Answer Question Preview", font = "Times 18 bold", fg = "blue" )
title.grid(row = 0, column = 2)
qtext = "Question text will read: "
ques = Label(preview, text = qtext)
ques.grid(row=1, column = 2)
ques2 = Label( preview, text = questionText.get("1.0",END))
let = 'A'
i = 1
for word in answerList:
prev = let + ": " + word
ans = Label(preview, text = prev)
ans.grid(row=1+i, column = 2)
let = chr(ord(let) + 1)
answerCor = "The correct answer(s): "
a = Label(preview, text = answerCor)
a.grid(row=4, column = 2)
b = Label(preview, text = cor.get)
b.grid(row=5, column = 2)
if num.get().isdigit():
number = int(num.get())
AnswerChoices = Label(top, text = "Answer Choices?", font = "Times 14 bold", fg = "blue")
AnswerChoices.grid(row = 6, column=4)
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
print answerList
correct = Label(top, text = "Correct Answer(s) (seperated by commas)",
font = "Times 14 bold", fg = "blue")
correct.grid(row =99 , column=4)
cor = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
cor.grid(row=100, column = 4)
else:
error = Tk()
w = 500
h = 100
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
error.geometry('%dx%d+%d+%d' % (w, h, x, y))
text = "ERROR: You must enter an integer number"
Label(error,text = text, fg = "red", font = "Times 16 bold").pack()
MyButton5 = Button(top, text="Preview Question", width=20, command = preview, anchor=S)
MyButton5.grid(row=102, column=5)
MyButton4 = Button(top, text="Finish and Add Question", width=20, command = add, anchor=S)
MyButton4.grid(row=102, column=2)
but = Button(top, text="Submit", width=10, command = multiple)
but.grid(row=6, column = 4)
top.mainloop()
def button():
MyButton21 = Button(quiz, text="Short Answer Question", width=20, command = short_answer)
MyButton21.grid(row=8, column=2)
MyButton22 = Button(quiz, text="True/False Question", width=20, command = true_false)
MyButton22.grid(row=8, column=4)
MyButton23 = Button(quiz, text="Multiple Choice Question", width=20, command = multiple_choice)
MyButton23.grid(row=9, column=2)
#MyButton24 = Button(quiz, text="Matching Question", width=20, command = matching)
#MyButton24.grid(row=9, column=4)
MyButton25 = Button(quiz, text="Ordering Question", width=20, command =order)
MyButton25.grid(row=10, column=2)
MyButton26 = Button(quiz, text="Fill in the Blank Question", width=20, command = fill_blank)
MyButton26.grid(row=10, column=4)
MyButton3 = Button(quiz, text="Finsh Quiz", width=10, command = quiz)
MyButton3.grid(row=12, column=3)
quiz = Tk()
w = 700
h = 300
ws = quiz.winfo_screenwidth()
hs = quiz.winfo_screenheight()
x = 0
y = 0
quiz.geometry('%dx%d+%d+%d' % (w, h, x, y))
quiz.title("eCampus Quiz Developer")
L1 = Label(quiz, text="Quiz Title?")
L1.grid(row=0, column=0)
E1 = Entry(quiz, bd = 5)
E1.grid(row=0, column=3)
name_file = E1.get()
name_file = name_file.replace(" ", "")
name_file = name_file + ".txt"
with open(name_file,"w") as data:
MyButton1 = Button(quiz, text="Submit", width=10, command = button)
MyButton1.grid(row=1, column=3)
quiz.mainloop()
I am trying to create the dictionary using this chunk of code:
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
I have even tried putting a loop in the preview function but that is when the last box was the only value contained in the dictionary. Any ideas would be appreciated
Please see my commeneted snippet below which demonstrates this:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.entry = Entry(self.root) #entry to input number of entries later
self.button = Button(self.root, text="ok", command=self.command) #calls command to draw the entry boxes
self.frame = Frame(self.root)
self.entry.pack()
self.button.pack()
self.frame.pack()
def command(self):
self.frame.destroy() #destroys frame and contents
self.frame = Frame(self.root) #recreates frame
self.text = [] #empty array to store entry boxes
for i in range(int(self.entry.get())):
self.text.append(Entry(self.frame, text="Question "+str(i))) #creates entry boxes
self.text[i].pack()
self.done = Button(self.frame, text="Done", command=self.dict) #button to call dictionary entry and print
self.done.pack()
self.frame.pack()
def dict(self):
self.dict = {}
for i in range(len(self.text)):
self.dict.update({self.text[i].cget("text"): self.text[i].get()})
#the above line adds a new dict entry with the text value of the respective entry as the key and the value of the entry as the value
print(self.dict) #prints the dict
root = Tk()
App(root)
root.mainloop()
The above asks the user how many entry widgets they want to create, fills a frame with those entry widgets and then iterates through the list which contains them on the press of a button, adding a new dictionary entry for each entry widget, where the key of the dict is the attribute text for each entry and the value of the dict is the value of each entry.
Related
I'm coding a GUI for inputting parameters, images and text all associated with a particular step (One single row per step) and then outputting it as JavaScript code to be used in another program. But this is beside my point:
I am having trouble forcing the column widths. It seems that both canv_1.grid_columnconfigure(6, weight=2) and canv_1.grid_columnconfigure(1, weight=0) do nothing. I'm trying to keep the width of the column 2nd from the left to a minimum. And I want column 6 to be twice as wide as the others.
import tkinter as tk
from tkinter import simpledialog,filedialog,colorchooser,messagebox,Frame,Button
from PIL import ImageTk, Image
import textwrap
root = tk.Tk()
load1 = Image.open("example.jpg")
root.render1 = ImageTk.PhotoImage(load1)
canv_1 = tk.Canvas(root, bg="gray")
canv_1.grid_rowconfigure(0, weight=1)
canv_1.grid_columnconfigure(6, weight=2)
canv_1.grid_columnconfigure(2, weight=0)
canv_1.grid(row=0, column=0, sticky="news")
canv_1.grid(row=1, column=0, sticky="news")
labels = ["Image", "Chapter #", "Chapter Title", "Step", "Slide", "Sequence Step", "Instructions"]
root.label_wid = []
font1 = ("arial", 15, "bold")
ch_text = []
def exportCode():
# Gather text input for each chapter
for i in range(0,5):
# Get the text (unwrapped) from a single input cell:
a_temp = instruction_col[i].get('1.0','10.0')
# Wrap the text at 54 characters, then append it to the list ch_text
ch_text.append(textwrap.wrap(a_temp,54))
# Create a new file
f = open("demofile2.js", "w")
# For each chapter
for i in range(1,5):
# Write to this file line by line
#
# stepID = str()
# stepHeading = "if(place==\""
for j in range(1,11):
tnum = str(j)
nline1st = " scopeSet(\"T"+tnum+"\",\"text\",\""
if (len(ch_text[i-1])<j):
nline2nd = ""
else:
nline2nd = ch_text[i-1][j-1]
f.write(nline1st+nline2nd+"\")\n")
f.close()
print("Code exported.")
for i in range(len(labels)):
root.label_wid.append(tk.Label(canv_1, font=font1, relief="raised", text=labels[i]).grid(row=0, column=i, sticky="we"))
root.images = [
ImageTk.PhotoImage(Image.open("example.jpg"))
for y in range(1,6)
]
def change_img(y):
#print(y)
#print(len(root.images))
root.img1 = filedialog.askopenfilename()
root.load_img1 = Image.open(root.img1)
root.render_img1 = ImageTk.PhotoImage(root.load_img1)
image_col[y]['image'] = root.render_img1
print(image_col[y]['image'])
print(image_col[y-1]['image'])
print(root.render_img1)
c1 = "#a9d08e"
c2 = "#8dd1bf"
image_col = [
tk.Button(
canv_1,
image=root.render1,
relief="raised",
bg="light gray",
command = lambda y=y: change_img(y),
)
for y in range(0, 5)
]
ChNum_col = [
tk.Entry(
canv_1,
bg = c1,
font = ("arial", 15))
for y in range(0, 5)
]
Title_col = [
tk.Entry(
canv_1,
bg = c1,
font = ("arial", 15))
for y in range(0, 5)
]
Step_col = [
tk.Entry(
canv_1,
bg = c1,
font = ("arial", 15))
for y in range(0, 5)
]
Slide_col = [
tk.Entry(
canv_1,
bg = c2,
font = ("arial", 15))
for y in range(0, 5)
]
SeqS_col = [
tk.Entry(
canv_1,
bg = c2,
font = ("arial", 15))
for y in range(0, 5)
]
instruction_col = [
tk.Text(
canv_1,
bg="white",
wrap="word",
font=("arial",15), width=20, height=10)
for y in range(0, 5)
]
example_text_1 = "The purpose of this app is for the user to select an image and designate the associated parameters and text before exporting it as a JavaScript file to be used in a separate program."
example_text_2 = " Here is another example of text that might be used. This can be used for a specific chapter to test this code. It's getting closer to being ready for use"
instruction_col[0].insert(1.0,example_text_1)
instruction_col[1].insert(1.0,example_text_2)
# for y, image_cell in enumerate(image_col, 1):
# image_cell.grid(row=y, column=0, sticky='news')
# for y, image_cell in enumerate(instruction_col, 1):
# image_cell.grid(row=y, column=6, sticky='news')
# above is same as below
for y in range(0,5):
image_col[y].grid(row=y + 1, column=0, sticky='news')
ChNum_col[y].grid(row=y + 1, column=1, sticky='news')
Title_col[y].grid(row=y + 1, column=2, sticky='news')
Step_col[y].grid(row=y + 1, column=3, sticky='news')
Slide_col[y].grid(row=y + 1, column=4, sticky='news')
SeqS_col[y].grid(row=y + 1, column=5, sticky='news')
instruction_col[y].grid(row=y+1, column=6, sticky='news')
# ================================================================================================
bt1 = tk.Button(canv_1, text="Export", font=font1, command=exportCode).grid(row=0, column=7)
load2 = Image.open("scroll-up.png")
root.render2 = ImageTk.PhotoImage(load2)
load3 = Image.open("scroll-down.png")
root.render3 = ImageTk.PhotoImage(load3)
scroll_up = tk.Button(canv_1, image=root.render2).grid(row=1, column=7, rowspan=2) # , sticky="n")
scroll_up = tk.Button(canv_1, image=root.render3).grid(row=3, column=7, rowspan=2) # , sticky="s")
root.mainloop()
First
As mentioned by
#jizhihaoSAMA
width must be set.
I configured all Entry widths as width = 1, that seemed to shrink the column the to minimum width that matches the width of the accompanying Label above it.
Second
In addition to weight, it seems you need uniform = 999 (or any number / string) that will identify the column as part of a group that will proportion the width according to weight = 1, wieght = 2 per respective column.
In the modified script I made column 7 as 5 times the width of column 1
import tkinter as tk
from tkinter import simpledialog,filedialog,colorchooser,messagebox,Frame,Button,PhotoImage
#from PIL import ImageTk, Image
import textwrap
root = tk.Tk()
#load1 = Image.open("example.jpg")
root.render1 = PhotoImage(file="yes.png")
canv_1 = tk.Canvas(root, bg="red")
## Here uniform = ... must be set ##
canv_1.grid_rowconfigure(0, weight=1,uniform = 999)
canv_1.grid_columnconfigure(6, weight=5, uniform = 999)
canv_1.grid_columnconfigure(2, weight=0, uniform = 999)
canv_1.grid(row=0, column=0, sticky="news")
canv_1.grid(row=1, column=0, sticky="news")
labels = ["Image", "Chapter #", "Chapter Title", "Step", "Slide", "Sequence Step", "Instructions"]
root.label_wid = []
font1 = ("arial", 15, "bold")
ch_text = []
def exportCode():
# Gather text input for each chapter
for i in range(0,5):
# Get the text (unwrapped) from a single input cell:
a_temp = instruction_col[i].get('1.0','10.0')
# Wrap the text at 54 characters, then append it to the list ch_text
ch_text.append(textwrap.wrap(a_temp,54))
# Create a new file
#f = open("demofile2.js", "w")
# For each chapter
for i in range(1,5):
# Write to this file line by line
#
# stepID = str()
# stepHeading = "if(place==\""
for j in range(1,11):
tnum = str(j)
nline1st = " scopeSet(\"T"+tnum+"\",\"text\",\""
if (len(ch_text[i-1])<j):
nline2nd = ""
else:
nline2nd = ch_text[i-1][j-1]
#f.write(nline1st+nline2nd+"\")\n")
#f.close()
print("Code exported.")
for i in range(len(labels)):
tmp = tk.Label(canv_1, font=font1, relief="raised", text=labels[i])
tmp.grid(row=0, column=i, sticky="we")
root.label_wid.append(tmp)
print(root.label_wid[0].winfo_reqwidth())
root.images = [PhotoImage(file="yes.png") for y in range(1,6)]
def change_img(y):
#print(y)
#print(len(root.images))
root.img1 = filedialog.askopenfilename()
root.load_img1 = Image.open(root.img1)
root.render_img1 = PhotoImage(root.load_img1)
image_col[y]['image'] = root.render_img1
print(image_col[y]['image'])
print(image_col[y-1]['image'])
print(root.render_img1)
c1 = "#a9d08e"
c2 = "#8dd1bf"
image_col = [ tk.Button(canv_1, image=root.render1,relief="raised",bg="light gray",command = lambda y=y: change_img(y),width = 1) for y in range(0, 5) ]
ChNum_col = [tk.Entry(canv_1,bg = c1,font = ("arial", 15),width = 1) for y in range(0, 5) ]
Title_col = [tk.Entry(canv_1,bg = c1,font = ("arial", 15),width = 1) for y in range(0, 5) ]
Step_col = [tk.Entry(canv_1,bg = c1,font = ("arial", 15),width = 1) for y in range(0, 5)]
Slide_col = [tk.Entry( canv_1, bg = c2,font = ("arial", 15),width = 1) for y in range(0, 5)]
SeqS_col = [tk.Entry(canv_1,bg = c2,font = ("arial", 15),width = 1) for y in range(0, 5)]
instruction_col = [ tk.Text( canv_1, bg="white",wrap="word", font=("arial",15), width=5, height=10) for y in range(0, 5)
]
example_text_1 = "The purpose of this app is for the user to select an image and designate the associated parameters and text before exporting it as a JavaScript file to be used in a separate program."
example_text_2 = " Here is another example of text that might be used. This can be used for a specific chapter to test this code. It's getting closer to being ready for use"
instruction_col[0].insert(1.0,example_text_1)
instruction_col[1].insert(1.0,example_text_2)
# for y, image_cell in enumerate(image_col, 1):
# image_cell.grid(row=y, column=0, sticky='news')
# for y, image_cell in enumerate(instruction_col, 1):
# image_cell.grid(row=y, column=6, sticky='news')
# above is same as below
for y in range(0,5):
image_col[y].grid(row=y + 1, column=0, sticky='news')
ChNum_col[y].grid(row=y + 1, column=1, sticky='news')
Title_col[y].grid(row=y + 1, column=2, sticky='news')
Step_col[y].grid(row=y + 1, column=3, sticky='news')
Slide_col[y].grid(row=y + 1, column=4, sticky='news')
SeqS_col[y].grid(row=y + 1, column=5, sticky='news')
instruction_col[y].grid(row=y+1, column=6, sticky='news')
# ================================================================================================
bt1 = tk.Button(canv_1, text="Export", font=font1, command=exportCode).grid(row=0, column=7)
#load2 = Image.open("scroll-up.png")
root.render2 = PhotoImage(file="yes.png")
#load3 = Image.open("scroll-down.png")
root.render3 = PhotoImage(file="yes.png")
scroll_up = tk.Button(canv_1, image=root.render2).grid(row=1, column=7, rowspan=2) # , sticky="n")
scroll_up = tk.Button(canv_1, image=root.render3).grid(row=3, column=7, rowspan=2) # , sticky="s")
root.mainloop()
Use width
I tried width earlier, but it didn't seem to work- possibly because I had empty columns? Now the code is working though:
ChNum_col = [
tk.Entry(
canv_1,
bg = c1,
width = 10,
font = ("arial", 15))
for y in range(0, 5)
]
Im making my own cypher encryption and I want to put the result into the entry field called output. Now im just using print() so I could test if I got a result. But that was only for testing. This is one of the first times I used Python so if there are some other things I could have done better please let me know :)
this is what I have so far.
from tkinter import *
#Make frame
root = Tk()
root.geometry("500x300")
root.title("Encryption Tool")
top_frame = Frame(root)
bottom_frame = Frame(root)
top_frame.pack()
bottom_frame.pack()
#Text
headline = Label(top_frame, text="Encryption Tool", fg='black')
headline.config(font=('Courier', 27))
headline.grid(padx=10, pady=10)
Key = Label(bottom_frame, text="Key:", fg='black')
Key.config(font=('Courier', 20))
Key.grid(row=1)
Text_entry = Label(bottom_frame, text="Text:", fg='black')
Text_entry.config(font=('Courier', 20))
Text_entry.grid(row=2)
Output_text = Label(bottom_frame, text="Output:", fg='black')
Output_text.config(font=('Courier', 20))
Output_text.grid(row=3)
Key_entry = Entry(bottom_frame)
Key_entry.grid(row=1, column=1)
Text_entry = Entry(bottom_frame)
Text_entry.grid(row=2, column=1)
Output_text = Entry(bottom_frame)
Output_text.grid(row=3, column=1)
#Encryption_button
def encrypt():
result = ''
text = ''
key = Key_entry.get()
text = Text_entry.get()
formule = int(key)
for i in range(0, len(text)):
result = result + chr(ord(text[i]) + formule + i * i)
result = ''
Encryption_button = Button(bottom_frame, text="Encrypt", fg='black')
Encryption_button.config(height = 2, width = 15)
Encryption_button.grid(row = 4, column = 0, sticky = S)
Encryption_button['command'] = encrypt
#Decryption_button
def decrypt():
result = ''
text = ''
key = Key_entry.get()
text = Text_entry.get()
formule = int(key)
for i in range(0, len(text)):
result = result + chr(ord(text[i]) - formule - i * i)
print(result)
result = ''
Decryption_button = Button(bottom_frame, text="Decrypt", fg="black")
Decryption_button.config(height = 2, width = 15)
Decryption_button.grid(row = 5, column = 0, sticky = S)
Decryption_button['command'] = decrypt
#Quit_button
def end():
exit()
Quit_button = Button(bottom_frame, text="Quit", fg='black')
Quit_button.config(height = 2, width = 15)
Quit_button.grid(row = 6, column = 0, sticky = S)
Quit_button['command'] = end
root.mainloop()
The most common way to do this with tkinter would be with a StringVar() object you can connect to the Entry object (Some documentation here).
output_entry_value = StringVar()
Output_text = Entry(bottom_frame, textvariable=output_entry_value)
Output_text.grid(row=3, column=1)
then you can .set() the result in the stringvar, and it will update in the entries you connected it to:
output_entry_value.set(result)
I am trying to set up validation on text entry boxes. Three of the boxes need to only accept integers and one text as a postcode. I am not sure whether to do this in a function previously defined or when the entry boxes are created. Also how would i make the values from the text entry boxes be accessable in the function QuoteCreation. All my code is below.
from tkinter import *
class quote():
def __init__(self, master):
self.master=master
self.master.title("Quote Screen")
self.master.geometry("2100x1400")
self.master.configure(background = "white")
self.Borras = PhotoImage(file = "Borras.Logo.2.gif") #sets up image
self.Borras.image = self.Borras
self.BorrasLabel = Label(self.master, image = self.Borras, bg = "white")#puts image onto label
self.BorrasLabel.place(anchor=NW)
self.Title = Label(self.master, text = "New Quote", font = ("calibri", 20), bg = "White")
self.Title.place(x=650, y = 10)
self.SubmitButton = PhotoImage(file = "Submit.Button.gif") #sets up image
self.SubmitButton.image = self.SubmitButton
self.SubmitButtonLabel = Button(self.master, image = self.SubmitButton, bg = "white", command= self.QuoteCreation)#puts image onto a button
self.SubmitButtonLabel.place(x=900, y=290)
PostCodeVar = StringVar()
PostCodeEntry = Entry(master,width=50, font=20, textvariable=PostCodeVar)
PostCodeEntry.place(x = 20, y = 150)
PostCodeVar.set("Please enter the Post Code")
PostCodeValue = PostCodeVar.get()
HeightVar = StringVar()
HeightEntry = Entry(master, width=50, font=20, textvariable=HeightVar)
HeightEntry.place(x = 20, y = 220)
HeightVar.set("Please enter the Height")
HeightValue = HeightVar.get()
LengthVar = StringVar()
LengthEntry = Entry(master, width=50, font=20, textvariable=LengthVar)
LengthEntry.place(x = 20, y = 290)
LengthVar.set("Please enter the Length")
LengthValue = LengthVar.get()
PitchVar = StringVar()
PitchEntry = Entry(master, width=50, font=20, textvariable=PitchVar)
PitchEntry.place(x = 20, y = 360)
PitchVar.set("Please enter the Pitch")
PitchValue = PitchVar.get()
RiseVar = StringVar()
RiseEntry = Entry(master, width=50, font=20, textvariable=RiseVar)
RiseEntry.place(x = 20, y = 430)
RiseVar.set("Please enter the Rise")
RiseValue = RiseVar.get()
self.SubmitButton = PhotoImage(file = "Submit.Button.gif")
self.SubmitButton.image = self.SubmitButton
self.SubmitButtonLabel = Button(self.master, image = self.SubmitButton, bg = "white", command= self.QuoteCreation)#puts image onto a button
self.SubmitButtonLabel.place(x=900, y=290)
def on_button(self):
print(self.entry.get())
def QuoteCreation(self):
print(' ')
def quitWindow(self):
self.master.destroy()
def backToWelcome(self):
self.master.destroy()
You would set up separate functions to deal with the validation, when the submit button is pressed.
So, as an example, your submit button may look a bit like this:
submitButton = Button(master, text="Submit", command=validation)
The validation, in your case would then want to carry out these checks:
def validation():
postcode = PostCodeVar.get()
length = LengthVar.get()
pitch = PitchVar.get()
rise = RiseVar.get()
if postcodeCheck(postcode) == True and length.isdigit() == True and pitch.isdigit() == True and rise.isdigit() == True:
#carry out chosen process
In your case, you can try setting the postcode, length, pitch and height variables before calling the function, and setting them as global. The postcode should be created, and if it is okay, the function should then:
return True
...so it matches the outcome of the if statement.
I hope this is what you were looking for, and can adapt the example to your specific problem!
from tkinter import *
window = Tk()
ia_answers= "trolol"
input_frame = LabelFrame(window, text="User :", borderwidth=4)
input_frame.pack(fill=BOTH, side=BOTTOM)
input_user = StringVar()
input_field = Entry(input_frame, text=input_user)
input_field.pack(fill=BOTH, side=BOTTOM)
ia_frame = LabelFrame(window, text="Discussion",borderwidth = 15, height = 100, width = 100)
ia_frame.pack(fill=BOTH, side=TOP)
user_says = StringVar()
user_text = Label(ia_frame, textvariable=user_says, anchor = NE, justify = RIGHT, bg="white")
user_text.pack(fill=BOTH, side=TOP)
ia_says = StringVar()
ia_text = Label(ia_frame, textvariable=ia_says, anchor = W, justify = LEFT, bg="white")
ia_text.pack(fill=BOTH, side=BOTTOM)
def Enter_pressed(event):
"""Took the current string in the Entry field."""
input_get = input_field.get()
input_user.set("")
user_says.set(input_get + "\n\n")
ia_says.set(ia_answers)
input_field.bind("<Return>", Enter_pressed)
window.mainloop()
Hi, i am trying to build a discussion Bot.
When I execute the code, the question in the input field and the answer get displayed correctly.
The problem is after entering the next sentence, the previous question/answer gets removed. Here is an example:
Hello Bot
Hello User
(then the text disappears)
How are you
Fine thank you
What i want :
Hello Bot
Hello User
(then the text stays in the frame)
How are you
Fine thank you
The issue occurs in line -
user_says.set(input_get + "\n\n")
ia_says.set(ia_answers)
You are replace users_says.set() and ia_says.set() resets the complete Labels , with the new value. Instead you should get the old value and append the new value to it and set it back, Example -
user_says.set(user_says.get() + input_get + "\n")
ia_says.set(ia_says.get() + ia_answers + "\n")
Or you can also create a new label for each new event and add it to the LabelFrame . Example -
from tkinter import *
window = Tk()
ia_answers= "trolol\n"
input_frame = LabelFrame(window, text="User :", borderwidth=4)
input_frame.pack(fill=BOTH, side=BOTTOM)
input_user = StringVar()
input_field = Entry(input_frame, text=input_user)
input_field.pack(fill=BOTH, side=BOTTOM)
ia_frame = LabelFrame(window, text="Discussion",borderwidth = 15, height = 100, width = 100)
ia_frame.pack(fill=BOTH, side=TOP)
user_says = StringVar()
user_text = Label(ia_frame, textvariable=user_says, anchor = NE, justify = RIGHT,
bg="white")
user_text.pack(fill=X)
ia_says = StringVar()
ia_text = Label(ia_frame, textvariable=ia_says, anchor = NW, justify = LEFT, bg="white")
ia_text.pack(fill=X)
user_texts = []
ia_texts = []
user_says_list = []
ia_says_list = []
def Enter_pressed(event):
"""Took the current string in the Entry field."""
input_get = input_field.get()
input_user.set("")
user_says1 = StringVar()
user_says1.set(input_get + "\n")
user_text1 = Label(ia_frame, textvariable=user_says1, anchor = NE, justify = RIGHT,
bg="white")
user_text1.pack(fill=X)
user_texts.append(user_text1)
user_says_list.append(user_says1)
ia_says1 = StringVar()
ia_says1.set(ia_answers)
ia_text1 = Label(ia_frame, textvariable=ia_says1, anchor = NW, justify = LEFT,
bg="white")
ia_text1.pack(fill=X)
ia_texts.append(ia_text1)
ia_says_list.append(ia_says1)
input_field.bind("<Return>", Enter_pressed)
window.mainloop()
I am trying to create a simple interface to access the name array with first, last, previous and next functionality. But the global variable I am using as a position tracker is not working. I have already referred to various question. Would really appreciate the help. Here is the code.
from tkinter import Tk, Label, Entry, Button, StringVar, IntVar
window = Tk()
name_array = [('a1','a2','a3'), ('b1','b2','b3'), ('c1','c2','c3'),('d1','d2','d3')]
global position_track
position_track = IntVar()
first_name = StringVar()
last_name = StringVar()
email = StringVar()
def return_value(pos):
first_name.set(name_array[pos][0])
last_name.set(name_array[pos][1])
email.set(name_array[pos][2])
def update_value(pos):
name_array[pos] = (first_name.get(), last_name.get(), email.get())
def first_value():
global position_track
return_value(0)
postion_track.set(0)
def last_value():
global position_track
return_value(-1)
postion_track.set(-1)
def next_value():
global position_track
if position_track.get() == len(name_array):
position_track.set(1)
temp = postion_track.get()
return_value(temp + 1)
postion_track.set(temp + 1)
def prev_value():
global position_track
if position_track.get() == -1:
position_track.set(len(name_array - 1))
temp = postion_track.get()
return_value(temp - 1)
postion_track.set(temp - 1)
label_first_name = Label(window, text = 'First Name:', justify = 'right', padx = 5)
entry_first_name = Entry(window, textvariable = first_name)
label_last_name = Label(window, text = 'Last Name:', justify = 'right', padx = 5)
entry_last_name = Entry(window, textvariable = last_name)
label_email = Label(window, text = 'Email Address:', justify = 'right', padx = 5)
entry_email = Entry(window, textvariable = email)
button_first = Button(window, text = 'First', command = first_value)
button_last = Button(window, text = 'Last', command = last_value)
button_prev = Button(window, text = 'Prev', command = prev_value)
button_next = Button(window, text = 'Next', command = next_value)
button_quit = Button(window, text = 'Quit')
button_quit.configure(command=window.destroy)
labels = [label_first_name, label_last_name, label_email]
entries = [entry_first_name, entry_last_name, entry_email]
buttons = [button_first, button_last, button_prev, button_next, button_last, button_quit]
for i in range(3):
labels[i].grid(row = i, column = 0, sticky = 'W')
entries[i].grid(row = i, column = 1, columnspan = 6)
for j in range(6):
buttons[j].grid(row = 3, column = j, sticky = 'E')
window.mainloop()
Too many typos. Plus, you don't need to declare a global in the outermost program space, just in the function defs. Corrected working code ->
from tkinter import Tk, Label, Entry, Button, StringVar, IntVar
window = Tk()
name_array = [('a1','a2','a3'), ('b1','b2','b3'), ('c1','c2','c3'),('d1','d2','d3')]
position_track = IntVar()
first_name = StringVar()
last_name = StringVar()
email = StringVar()
def return_value(pos):
first_name.set(name_array[pos][0])
last_name.set(name_array[pos][1])
email.set(name_array[pos][2])
def update_value(pos):
name_array[pos] = (first_name.get(), last_name.get(), email.get())
def first_value():
global position_track
return_value(0)
position_track.set(0)
def last_value():
global position_track
return_value(-1)
position_track.set(-1)
def next_value():
global position_track
if position_track.get() == len(name_array):
position_track.set(1)
temp = position_track.get()
return_value(temp + 1)
position_track.set(temp + 1)
def prev_value():
global position_track
if position_track.get() == -1:
position_track.set(len(name_array) - 1)
temp = position_track.get()
return_value(temp - 1)
position_track.set(temp - 1)
label_first_name = Label(window, text = 'First Name:', justify = 'right', padx = 5)
entry_first_name = Entry(window, textvariable = first_name)
label_last_name = Label(window, text = 'Last Name:', justify = 'right', padx = 5)
entry_last_name = Entry(window, textvariable = last_name)
label_email = Label(window, text = 'Email Address:', justify = 'right', padx = 5)
entry_email = Entry(window, textvariable = email)
button_first = Button(window, text = 'First', command = first_value)
button_last = Button(window, text = 'Last', command = last_value)
button_prev = Button(window, text = 'Prev', command = prev_value)
button_next = Button(window, text = 'Next', command = next_value)
button_quit = Button(window, text = 'Quit')
button_quit.configure(command=window.destroy)
labels = [label_first_name, label_last_name, label_email]
entries = [entry_first_name, entry_last_name, entry_email]
buttons = [button_first, button_last, button_prev, button_next, button_last, button_quit]
for i in range(3):
labels[i].grid(row = i, column = 0, sticky = 'W')
entries[i].grid(row = i, column = 1, columnspan = 6)
for j in range(6):
buttons[j].grid(row = 3, column = j, sticky = 'E')
window.mainloop()