Python Tkinterprogramm import to a new file throws a error - python

i have a problem with the user-output of my tkinter gui.
First of all it works, but there is a huge problem with the import to a new py file. It throws a Error ().
Traceback (most recent call last):
File "F:\Python_Projekt\Übung\Plus\test.py", line 4, in <module>
tk = own.get_start()
File "F:\Python_Projekt\Übung\Plus\plus_window_pack2.py", line 31, in get_start
sel = ListBox1.curselection()
File "C:\Users\nox\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 2782, in curselection
return self._getints(self.tk.call(self._w, 'curselection')) or ()
_tkinter.TclError: invalid command name ".!frame.!frame.!listbox"
I know there is a problem with my ListBox but i have no clue how to handle it. I need the used output for my new script. So i could work with it.
from tkinter import*
import tkinter as tk
window = Tk()
rahmen1 = Frame(master = window) #, bg='black'
rahmen1.pack(side='top', padx=5, pady=5)
rahmen2 = Frame(master = rahmen1) #, bg= 'yellow'
rahmen2.pack(side='left', padx=5, pady=5)
def get_start():
selection=ListBox1.curselection()
picked = selection[0]
used = ListBox1.get(picked) #-------user-input
print(used)
return used
####################----------------------------------------------------
List = ['Dax','Dow','EUR/USD', 'Gold', 'Silber','EUR/JPY','USD/JPY']
scrollbar1 = Scrollbar(rahmen2) # ,bg='green'
scrollbar1.pack(padx = 1,side = 'right',fill=Y)
ListBox1 = Listbox(rahmen2,exportselection = False)
ListBox1.config( yscrollcommand = scrollbar1.set, width = 40)
scrollbar1.config( command = ListBox1.yview) # ,bg='blue'
for i in List:
ListBox1.insert(tk.END, str(i))
ListBox1.pack(padx = 1,)
###################------------------------------------------------
Button1 = Button(rahmen2,text='Get Data', font = 'bold')
Button1.config (width=40, height = 3, command = get_start)
Button1.pack( )
window.mainloop()
I changed the code to get the important part. For a better understanding of my problem.
if i want to get the user-input it thorw's me the error.

Try this. I have added a simple check to make sure something's selected (I'm not sure what the error at the top of your question's about though):
def get_start():
selection=ListBox1.curselection()
if len (selection) != 0:
picked = selection[0]
used = ListBox1.get(picked) #-------user-input
print(used)
return used
EDIT:
This checks every x seconds (defined by UPDATE_TIME) for checkbox updates
UPDATE_TIME = 0.1
from tkinter import*
import tkinter as tk
import threading, time
window = Tk()
rahmen1 = Frame(master = window) #, bg='black'
rahmen1.pack(side='top', padx=5, pady=5)
rahmen2 = Frame(master = rahmen1) #, bg= 'yellow'
rahmen2.pack(side='left', padx=5, pady=5)
def get_start():
print (previous)
return previous
def get_update ():
global previous
try:
while True:
selection=ListBox1.curselection()
if len (selection) == 0: previous = None
else:
picked = selection[0]
previous = ListBox1.get(picked) #-------user-input
time.sleep (UPDATE_TIME)
except: pass
####################----------------------------------------------------
List = ['Dax','Dow','EUR/USD', 'Gold', 'Silber','EUR/JPY','USD/JPY']
scrollbar1 = Scrollbar(rahmen2) # ,bg='green'
scrollbar1.pack(padx = 1,side = 'right',fill=Y)
ListBox1 = Listbox(rahmen2,exportselection = False)
ListBox1.config( yscrollcommand = scrollbar1.set, width = 40)
scrollbar1.config( command = ListBox1.yview) # ,bg='blue'
for i in List:
ListBox1.insert(tk.END, str(i))
ListBox1.pack(padx = 1,)
###################------------------------------------------------
Button1 = Button(rahmen2,text='Get Data', font = 'bold')
Button1.config (width=40, height = 3, command = get_start)
Button1.pack ()
threading.Thread (target = get_update).start ()
window.mainloop()

Related

I'm unable to get a string out of tkinter entrybox

import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame,text = "Print", command = lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame,height = 5, width = 20)
freek.pack()
input_a = freek.get(1.0, "end-1c")
print(input_a)
fruit = 0
fad = input_a[fruit:fruit+1]
print(fad)
schepje = len(input_a.strip("\n"))
print(schepje)
def zandkasteel():
lbl.config(text = "Ingevulde string: "+input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint()
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text = "")
lbl.pack()
frame.mainloop()
I need to get the string that was entered into the text entry field freek. I have tried to assign that string to input_a, but the string doesn't show up.
Right now, input_a doesn't get anything assigned to it and seems to stay blank. I had the same function working before implementing a GUI, so the problem shouldn't lie with the def zandkasteel.
To be honest I really don't know what to try at this point, if you happen to have any insights, please do share and help out this newbie programmer in need.
Here are some simple modifications to your code that shows how to get the string in the Text widget when it's needed — specifically when the zandkasteel() function gets called in response to the user clicking on the Print button.
import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame, text="Print", command=lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame, height=5, width=20)
freek.pack()
def zandkasteel():
input_a = freek.get(1.0, "end-1c")
print(f'{input_a=}')
fruit = 0
fad = input_a[fruit:fruit+1]
print(f'{fad=}')
schepje = len(input_a.strip("\n"))
print(f'{schepje=}')
lbl.config(text="Ingevulde string: " + input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint(1, 3)
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text="")
lbl.pack()
frame.mainloop()

Error: "Assigning result of a function call where the function has no return" for a simple login GUI

I'm trying to make a simple login GUI which will have "two-factor authentication". I'm having a problem with line 24 where I get the error "Assigning result of a function call, where the function has no return"
Here is the code:
import tkinter as tk
def test_my_button():
frame_auth.tkraise()
root = tk.Tk()
root.wm_geometry("200x200")
frame_login = tk.Frame(root)
frame_login.grid(row = 0, column = 0)
lbl_username = tk.Label(frame_login, text='Username:')
lbl_username.pack()
ent_username = tk.Entry(frame_login, bd=3)
ent_username.pack(pady=5)
lbl_password = tk.Label(frame_login, text="Password:")
lbl_password.pack()
ent_password = tk.Entry(frame_login, bd=3, show = "*")
ent_password.pack(pady=5)
###ERROR HERE###
btn_login = tk.Button(frame_login, text = "Login", command = test_my_button).pack()
frame_auth = tk.Frame(root)
frame_auth.grid(row = 0, column = 0)
frame_login.tkraise()
root.mainloop()
All help is appreciated!
That's a linter warning, not an error. It's telling you that pack doesn't return anything, so it doesn't make sense to assign it to a variable.
You want the call to pack on its own line after assigning btn_login:
btn_login = tk.Button(frame_login, text = "Login", command = test_my_button)
btn_login.pack()

import error no module named tkinter issue for latest Python version 3.8.2

I have been trying to resolve the error:
ImportError: No module named tkinter
however no solutions from previous questions seem to be working at all.
I have tried :
sudo apt-get install python3-tk
and tkinter installed successfully, yet the issue remains.
I've tried making the t in tkinter uppercase as i'm using Python 3.8.2 yet that did not work.
I have also tried reinstalling/repairing Python as tkinter supposedly comes with the latest Python versions.
Attempting to open my file with python3 main.py results in the following error
Traceback (most recent call last):
File "main.py", line 95, in
window = Tk()
File "/usr/lib/python3.6/tkinter/init.py", line 2023, in init
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
I have also tried installing tkinter through its installer for
Windows, the installer works yet I still have the same issue. I have also tried updating my pip. Running pip list does not display tkinter.
Below is my main.py file.
from tkinter import *
from tkinter import filedialog
from tkinter.ttk import Progressbar
import tkinter.font as font
import os.path
from modify_data_pandas import get_column_headings
from modify_data_pandas import scan_file
#Closes window
def close_window():
window.destroy()
#Function checks if the file exists, changes label
def is_valid(*args):
if os.path.isfile(input_file_path.get()):
valid_confirm_lbl.config(text="File Found!")
valid_confirm_lbl.config(fg="green")
return 1
else:
valid_confirm_lbl.config(text="File Not Found")
valid_confirm_lbl.config(fg="red")
return 0
#Sets progress bar value
def setbar(value):
progress_bar['value'] = value
#Gets the current selection in the list box
def add_selection():
if is_valid():
items = headers_listbox.curselection()
already_selected = headers_listbox_selected.get(0, END)
for item in items:
if headers[item] not in already_selected:
headers_listbox_selected.insert(END, headers[item])
#Gets the current selection in the list box
def remove_selection():
if is_valid():
items = headers_listbox_selected.curselection()
pos = 0
for i in items :
idx = int(i) - pos
headers_listbox_selected.delete(idx,idx)
pos = pos + 1
#Add all items in listbox to selection
def add_all():
if is_valid():
items = headers_listbox.get(0, END)
for item in items:
if item not in headers_listbox_selected.get(0, END):
headers_listbox_selected.insert(END, item)
#Remove all items in selection listbox
def remove_all():
if is_valid():
headers_listbox_selected.delete(0, END)
#Scans the file for sensitive data
def scan():
if is_valid():
print("Scan")
change_row, change_col, change_type = scan_file(input_file_path, headers_listbox_selected.get(0, END))
#Anonymizes the file
def anonymize():
if is_valid():
print("do anonymize")
#Opens file dialog to pick a csv file
def choose_file():
input_file_name = filedialog.askopenfilename(initialdir = "/", title = "Select file",filetypes = (("CSV files","*.csv"),))
input_file.delete(0, END)
input_file.insert(END, input_file_name)
#Analyzes the file for sensitive data
def analyze_file():
if is_valid():
headers_listbox.delete(0, END)
headers_listbox_selected.delete(0, END)
global headers
headers = get_column_headings(input_file_path)
#headers = list of column headings from selected file
for item in headers:
headers_listbox.insert(END, item)
#Call function that checks each cell for sensitive data
return 1
else:
return 0
#Configure GUI Window
window = Tk()
window.title("CSV Anonymizer")
window.geometry("413x800")
lbl_frame = Frame(window)
lbl_frame.grid(column=0, row=1)
listbox_lbl_frame = Frame(window)
listbox_lbl_frame.grid(column=0, row=5, pady=5)
listbox_frame = Frame(window)
listbox_frame.grid(column=0, row=6)
listbox_btn_frame = Frame(window)
listbox_btn_frame.grid(column=0, row=7)
listbox_btn_frame_2 = Frame(window)
listbox_btn_frame_2.grid(column=0, row=8)
#Label: "File:"
input_file_prompt = Label(lbl_frame, text="File:",anchor=W, justify=LEFT)
input_file_prompt.pack(side = LEFT)
input_file_prompt.config(width=20)
#Label: "File Not Found / File Found!"
valid_confirm_lbl = Label(lbl_frame, text="", anchor=E, justify=RIGHT)
valid_confirm_lbl.pack(side = RIGHT)
valid_confirm_lbl.config(width=20)
#Create stringvar so file path is verified upon change
input_file_path = StringVar()
#Text Field to display/enter Input File Name
input_file = Entry(window, textvariable=input_file_path, width=10)
input_file.grid(column=0, row=2, padx=20)
input_file.config(width=40)
#Checks if the file is valid upon change
input_file_path.trace_add("write", is_valid)
#Button: "Click to Select a File", opens file browser to select a file
choose_file_btn = Button(window, text = "Click to Select a File", command = choose_file)
select_btn_font = font.Font(family='Helvetica', size=20, weight='bold')
choose_file_btn['font'] = select_btn_font
choose_file_btn.grid(column = 0, row = 0, padx=20, pady=20)
choose_file_btn.config(height=3,width=30)
#Button: "Use This File", starts analyze_file func
use_file_btn = Button(window, text = "Use This File", command = analyze_file)
use_file_btn.grid(column = 0, row = 3, padx=20, pady=(8, 10))
use_file_btn.config(width=13, height=2)
#Label "Select the columns you would like to anonymize"
select_columns_lbl = Label(window, text="Select the columns you would like to anonymize")
bold_font = font.Font(family='Helvetica', size=15, weight='bold')
select_columns_lbl['font'] = bold_font
select_columns_lbl.grid(column=0, row=4)
select_columns_lbl.config(width=40)
#Labels state listbox titles
column_headings_lbl = Label(listbox_lbl_frame, text = "Column Headings")
column_headings_lbl.pack(side=LEFT)
column_headings_lbl.config(width=20)
selected_column_headings_lbl = Label(listbox_lbl_frame, text = "Selected")
selected_column_headings_lbl.pack(side=RIGHT)
selected_column_headings_lbl.config(width=20)
#Left listbox, shows column headings from selected file
headers_listbox = Listbox(listbox_frame, selectmode = MULTIPLE)
headers_listbox.pack(side=LEFT)
headers_listbox.config(width=20)
#Right listbox, shows selected column headings
headers_listbox_selected = Listbox(listbox_frame, selectmode = MULTIPLE)
headers_listbox_selected.pack(side=RIGHT)
headers_listbox_selected.config(width=20)
#Buttons to add and remove current selections from respective listboxes
add_selection_btn = Button(listbox_btn_frame, text = "Add Current Selection", command = add_selection)
add_selection_btn.pack(side=LEFT)
add_selection_btn.config(width=20)
remove_selection_btn = Button(listbox_btn_frame, text = "Remove Current Selection", command = remove_selection)
remove_selection_btn.pack(side=RIGHT)
remove_selection_btn.config(width=20)
#Buttons to add and remove all items from their respective listboxes
add_all_btn = Button(listbox_btn_frame_2, text = "Add All", command = add_all)
add_all_btn.pack(side=LEFT)
add_all_btn.config(width=20)
remove_all_btn = Button(listbox_btn_frame_2, text = "Remove All", command = remove_all)
remove_all_btn.pack(side=RIGHT)
remove_all_btn.config(width=20)
#Label "Select the columns you would like to anonymize"
get_suggestions_lbl = Label(window, text="Would you like to scan the file for sensitive data?")
get_suggestions_lbl['font'] = bold_font
get_suggestions_lbl.grid(column=0, row=9, pady=(15, 10))
get_suggestions_lbl.config(width=40)
#Button: "Scan File", starts scan_file func
get_suggestions_btn = Button(window, text = "Scan File", command = scan)
get_suggestions_btn.grid(column = 0, row = 10, pady=(0, 10))
get_suggestions_btn.config(width=20, height=2)
#Button: "Anonymize", starts anonymize func
anonymize_btn = Button(window, text = "Anonymize", command = anonymize)
anonymize_btn.grid(column = 0, row = 11, pady=(0, 10))
anonymize_btn.config(width=20, height=2)
progress_bar = Progressbar(window, orient = 'horizontal', length = 286, mode = 'determinate')
progress_bar.grid(column = 0, row = 12, pady =2)
progress_bar["maximum"] = 100
progress_bar["value"] = 0
#Button to quit the program
quit_btn = Button(window, text = "Quit", command = close_window)
quit_btn.grid(column = 0, row = 20)
quit_btn.config(width=10, height=2)
window.mainloop()
Any ideas?

Random tkinter window opening on if/else statement

I'm wondering if I got my if else statement wrong or if its a tkinter issue. I want it so that if a 0 is left in any or all boxes, it gives an error message. But after the error message is closed, it opens a random blank window. This is my code. The specific area is the if else statement within the function valueget()
import tkinter as tk
def mainwindow():
mainwindow = tk.Tk()
mainwindow.title('Enter values')
mainwindow.geometry('160x110')
mainwindow.config(bg='#aaf0d1')
tk.Label(mainwindow, text = 'Enter a', font = ('verdana'), bg='#aaf0d1').grid(row=0)
tk.Label(mainwindow, text = 'Enter b', font = ('verdana'), bg='#aaf0d1').grid(row=1)
tk.Label(mainwindow, text = 'Enter c', font = ('verdana'), bg='#aaf0d1').grid(row=2)
getA = tk.IntVar()
aBox = tk.Entry(mainwindow, textvariable = getA, width=3, bg='#aaf0d1')
aBox.grid(row=0, column=1)
aBox.config(highlightbackground='#aaf0d1')
getB = tk.IntVar()
bBox = tk.Entry(mainwindow, textvariable = getB, width=3, bg='#aaf0d1')
bBox.grid(row=1, column=1)
bBox.config(highlightbackground='#aaf0d1')
getC = tk.IntVar()
cBox = tk.Entry(mainwindow, textvariable = getC, width=3, bg='#aaf0d1')
cBox.grid(row=2, column=1)
cBox.config(highlightbackground='#aaf0d1')
button = tk.Button(mainwindow, text='Obtain roots', command = lambda: valueget(), font = ('verdana'), highlightbackground='#aaf0d1')
button.grid(row=4)
button.config(bg='#aaf0d1')
def valueget():
readA = getA.get()
readB = getB.get()
readC = getC.get()
intA = int(readA)
intB = int(readB)
intC = int(readC)
negroot = (readB**2)-(4*readA*readC)
quadformulaplus = (-readB + (pow(negroot,0.5)))/(2*readA) #quad forumla
quadformulaminus = (-readB - (pow(negroot,0.5)))/(2*readA) #quad forumla
messagewindow = tk.Tk()
messagewindow.geometry('290x50')
messagewindow.title('Roots of the equation')
messagewindow.config(bg='#aaf0d1')
if readA == 0 or readB==0 or readC==0 or (readA==0 and readB==0 and readC==0):
errorwindow = tk.messagebox.showerror(message='none').pack()
else:
label = tk.Label(messagewindow, text = f'The roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}', bg='#aaf0d1', font = ('verdana'))
label.grid(row=1)
closebutton = tk.Button(messagewindow, text='Close', command = lambda: messagewindow.destroy(), font = ('verdana'), highlightbackground='#aaf0d1')
closebutton.grid(row=2)
closebutton.config(bg='#aaf0d1')
messagewindow.mainloop()
# print(f'the roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}')
mainwindow.mainloop()
def startup():
startpage = tk.Tk()
startpage.title('Solver')
photo = tk.PhotoImage(file = r"/Users/isa/Desktop/DiffEqns/cover.png") #image load
coverbutton = tk.Button(startpage, image = photo, command = lambda: [startpage.destroy(), mainwindow()])
coverbutton.pack()
coverbutton.configure(highlightbackground='#aaf0d1')
startpage.mainloop()
startup()
Here's a basic idea of what I would do:
import tkinter as tk
from tkinter import messagebox
def mainwindow(root):
# Creates a toplevel window
mainwindow = tk.Toplevel()
mainwindow.protocol("WM_DELETE_WINDOW", root.destroy) # This overrides the "X" being clicked to also destroy the root window.
root.withdraw() # "Hides" the root window, leaving it (and mainloop) running in the background.
mainwindow.title('Enter values')
mainwindow.geometry('160x110')
mainwindow.config(bg='#aaf0d1')
# Since all three of the labels/entries are the same
# we can save space by generating them in a loop
entry_items = ('Enter a', 'Enter b', 'Enter c')
values = []
for x, item in enumerate(entry_items): # Using enumerate and x to assign rows
tk.Label(mainwindow, text = item,
font = ('verdana'), bg='#aaf0d1').grid(row=x) # Row assigned to x.
values.append(tk.StringVar()) # Appended StringVar to list.
tk.Entry(mainwindow,
textvariable = values[-1], # Uses the last value appended to the values list.
highlightbackground='#aaf0d1',
width=3,
bg='#aaf0d1').grid(row=x, column=1) # Row assigned to x.
tk.Button(mainwindow,
text='Obtain roots',
command = lambda vals = values: valueget(vals), # Here the button command is assigned with the values list
font = ('verdana'), bg='#aaf0d1',
highlightbackground='#aaf0d1').grid(row=3) # we know there are 3 items before this.
mainwindow.lift() # This is a method of bringing a window to the front
def valueget(vals):
# This line gets the values from the StringVars, converts them to ints,
# and returns them to their respective variables.
try:
readA, readB, readC = [int(val.get()) for val in vals]
except ValueError:
messagebox.showerror(title="Number Error", message='Values must be numbers')
return
# Here the variables are checked to see if they are 0
# Since each one is being checked if it is 0, there is no need to check if they are all 0.
for val in (readA, readB, readC):
if val == 0:
# If they are 0, shows an error message
messagebox.showerror(title="Zero Error", message='Values must not be zero')
return
# Creates a toplevel to display the results
messagewindow = tk.Toplevel()
messagewindow.title('Roots of the equation')
messagewindow.config(bg='#aaf0d1')
negroot = (readB**2)-(4*readA*readC)
quadformulaplus = (-readB + (pow(negroot,0.5)))/(2*readA) #quad forumla
quadformulaminus = (-readB - (pow(negroot,0.5)))/(2*readA) #quad forumla
tk.Label(messagewindow,
text = f'The roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}',
bg='#aaf0d1',
font = ('verdana')).pack(padx = 5, pady = 2)
tk.Button(messagewindow,
text='Close',
command = messagewindow.destroy, # There is no need for a lambda for this.
font = ('verdana'),
bg = '#aaf0d1',
highlightbackground='#aaf0d1').pack(padx = 5, pady = 2)
# print(f'the roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}')
messagewindow.lift() # This is a method of bringing a window to the front
def startup():
startpage = tk.Tk()
startpage.title('Solver')
# COMMENTED OUT FOR TESTING
#photo = tk.PhotoImage(file = r"/Users/isa/Desktop/DiffEqns/cover.png") #image load
coverbutton = tk.Button(startpage,
# COMMENTED OUT FOR TESTING
#image = photo,
text = "TESTING", # HERE FOR TESTING
highlightbackground='#aaf0d1',
command = lambda root = startpage: mainwindow(root)).pack() # Passes the startpage to the mainwindow function.
startpage.mainloop() # The only mainloop you need.
startup()
I would recommend to improve the readability of the if-else statement for a start.
coefficients = [readA, readB, readC]
if sum(coefficients): # If they all are all zeros this will be False
if min(coefficients): # If any one is zero, this will be False
label = tk.Label(messagewindow, text = f'The roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}', bg='#aaf0d1', font = ('verdana'))
label.grid(row=1)
closebutton = tk.Button(messagewindow, text='Close', command = lambda: messagewindow.destroy(), font = ('verdana'), highlightbackground='#aaf0d1')
closebutton.grid(row=2)
closebutton.config(bg='#aaf0d1')
else:
errorwindow = tk.messagebox.showerror(message='none').pack()
else:
errorwindow = tk.messagebox.showerror(message='none').pack()

How to save a data after closing a window?

I'm trying to make some GUI on Python3 with tkinter. So far I have Main Window and 'Test' button on it, which opens second window. Second window has entry, label, save and close buttons. When you type something in entry and press save button, label shows the text you typed in entry. But after closing this window and opening it again, label shows nothing. How do I make this label to show the text that were typed last time before closing? For example, I type 'Hi' in entry, press 'Save', then I press 'Close', then I open this window again and label shows 'Hi'
import tkinter as tk
def save_data(entry, t):
t.config(text = entry.get())
def close_action(current_window):
current_window.destroy()
def insertMainInfo():
new_window = tk.Tk()
new_window.geometry("307x131")
new_window.title("TestWindow")
test_entry = tk.Entry(new_window)
test_entry.place(relx = 0.283, rely = 0.1, height = 24, width = 127)
text = tk.Label(new_window)
text.place(relx = 0.283, rely = 0.25, height = 24, width = 127)
save_button = tk.Button(new_window, command = lambda: save_data(test_entry, text))
save_button.place(relx=0.283, rely=0.45, height=24, width=127)
save_button.configure(text = "Save")
close = tk.Button(new_window, command = lambda: close_action(new_window))
close.place(relx=0.283, rely=0.687, height=24, width=127)
close.configure(text = "Close")
new_window.mainloop()
if __name__ == '__main__':
top = tk.Tk()
top.geometry("307x131+557+330")
top.resizable(width=False, height=False)
top.title("MainWindow")
new_window_button = tk.Button(top, command = insertMainInfo)
new_window_button.place(relx=0.283, rely=0.687, height=24, width=127)
new_window_button.configure(text = "Test")
main_label = tk.Label(top)
main_label.place(relx=0.033, rely=0.153, height=41, width=284)
main_label.configure(text = "TestLabel")
top.mainloop()
I have to confess that your question heading is a bit ambiguity.
If you just want to update a label of last entry, here a simple way of modifying your code.
As advised, as a good practice we only have one Tk() in a program, other new windows or pop-up windows should use Toplevel() of tkinter class; So I use this in your insertMainInfo() function.
The point here is to define a variable, I called last_entry and initially is empty or ‘’. Use this as parameter in new_window button in main program (after if __name__ == '__main__': ) to this variable (I also add lambda function here).
Then we define it as global in save_data function, so as it can be known later by other functions or main program as the last entry before new_window is closed.
Here I modify your code as said above, and I have tested it, and it works as expected.
import tkinter as tk
def save_data(entry, t):
global last_entry
last_entry = entry.get()
t.config(text = last_entry)
def close_action(current_window):
current_window.destroy()
def insertMainInfo(last_entry):
new_window = tk.Toplevel()
new_window.geometry("307x131")
new_window.title("TestWindow")
test_entry = tk.Entry(new_window)
test_entry.place(relx = 0.283, rely = 0.1, height = 24, width = 127)
text = tk.Label(new_window, text=last_entry)
text.place(relx = 0.283, rely = 0.25, height = 24, width = 127)
save_button = tk.Button(new_window, command = lambda: save_data(test_entry, text))
save_button.place(relx=0.283, rely=0.45, height=24, width=127)
save_button.configure(text = "Save")
close = tk.Button(new_window, command = lambda: close_action(new_window))
close.place(relx=0.283, rely=0.687, height=24, width=127)
close.configure(text = "Close")
new_window.mainloop()
# --- A Simple Data Structure ---
last_entry = ''
if __name__ == '__main__':
top = tk.Tk()
top.geometry("307x131+557+330")
top.resizable(width=False, height=False)
top.title("MainWindow")
new_window_button = tk.Button(top, command = lambda: insertMainInfo(last_entry))
new_window_button.place(relx=0.283, rely=0.687, height=24, width=127)
new_window_button.configure(text = "Test")
main_label = tk.Label(top)
main_label.place(relx=0.033, rely=0.153, height=41, width=284)
main_label.configure(text = "TestLabel")
top.mainloop()

Categories