首页 > 解决方案 > 将 tkinter 框输入写入 excel 单元格

问题描述

问题陈述:通过 tkinter 框的用户输入未写入 excel 表!

我的主要问题是 .get() 语句。无论输入类型如何,我只想将用户输入打印在 excel 上。

提前致谢。

from tkinter import *


# define this function to close the window after text submition
def close_window():
    window.destroy()

#window dimentions  
window = Tk()
window.title("My App")
window.geometry('350x200')

v = StringVar()
user_data = Entry(textvariable=v)
user_data.pack() 
ans = v.get()

# I need this input on excel

f= open('sht.csv','w')
f.write(ans)
f.close()


button = Button(text="Submit", command = close_window)
button.pack()

window.mainloop()

标签: python-3.xtkinter

解决方案


因为你调用了close_window函数,试试这个,我添加了函数write_to。无论如何,我建议采用 OO 方法。

from tkinter import *


# define this function to close the window after text submition
def close_window():
    window.destroy()

#window dimentions  
window = Tk()
window.title("My App")
window.geometry('350x200')

v = StringVar()
user_data = Entry(textvariable=v)
user_data.pack() 


# I need this input on excel
def write_to():
    ans = v.get()
    f= open('sht.csv','w')
    print(ans)
    f.write(ans)
    f.close()


button = Button(text="Submit", command = write_to)
button.pack()

window.mainloop()

推荐阅读