I don't understand the movement of the x button (close window button) on the tkinter and the button I created myself.

Asked 2 years ago, Updated 2 years ago, 139 views

The goal is to retrieve the value entered in the text box from the GUI image and write it to a CSV file.It consists of a screen source file (tkinter.py) and a source file (merge.py) for writing to CSV.
Currently, word1 can be replaced with a value, but
You can get the value of the text box by pressing the x button (Close window button) in the upper right corner of the screen, but you cannot get the value by pressing the Close button created here.The CSV does not write when you press the Close button.I'd like to know how to do it because I don't know if I haven't been able to get the value or if I'm in the middle of processing.

sample_tkinter.py

import tkinter ask
import sys

define_menu():
    sys.exit()

root=tk.Tk()
root.geometry ("300x300")

entry=tk.Entry()
entry.place(x=20,y=30)

button=tk.Button(text="OK")
button.place (x=150, y=29)

word1=""    
def click():
    global word1
    word1 = entry.get()
   
    label=tk.Label(text="Confirmed")
    label.place(x=20,y=50)

button ["command" ] = click

Label_Blanc=tk.Label(root, text=u')
Label_Blanc.grid (row=50, column=50)
finish_menu_Button=tk.Button(root, text=u'Close')
finish_menu_Button ["command"] = finish_menu
finish_menu_Button.place(x=30,y=60)


root.mainloop()

merge.py

import csv

from sample_tkinter import word1

with open("sample.csv", "w", encoding="shift-jis") ascsvfile:
    writer=csv.writer(csvfile, lineterminator="\n")
    
    writer.writerow ([word1])
print(word1)

python csv tkinter

2022-09-30 19:39

1 Answers

When calling sample_tkinter.py from merge.py, the contents of word1 are not displayed because sys.exit has terminated Python itself.
The code you asked does not run print(word1).

Rewrite tkinter.Tk#destroy from the finish_menu function as follows:
destroy is referenced in the A Hello World Program official documentation.

def finish_menu():
    # sys.exit()
    root.destroy()

The following sample code used for demonstration may also be helpful.

sample code

import tkinter ask
import sys

root=tk.Tk()
root.geometry ("300x100")

# Button to call sys.exit()
button_exit=tk.Button(text="Exit", command=sys.exit)
button_exit.place(x=0,y=0)

# button to call root.destroy()
button_destroy=tk.Button(text="Destroy", command=root.destroy)
button_destroy.place(x=150,y=0)

root.mainloop()

# If sys.exit, exit python with mainloop
# If you do root.destroy, you just close the window and exit mainloop, so continue to do the following.

print("Exit Button Does Not Display")


2022-09-30 19:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.