如何使用tkinter和mysql(csv)

2024-05-19 01:44:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个窗口,你可以ping不同的地址(总共有4个)。尝试编写一个单独的函数,将文本格式的数据一起输出到csv文件。不起作用:( 在文件夹中创建了一个csv文件,其中包含代码,我称之为'result.csv',但它毫无意义

问题是:如何编写一个函数,以便在tkinter中显示ping结果时,它们也以csv格式显示,或者直接显示在mysql表中?(有条件地位于代码所在的文件夹中)

检查代码:

from tkinter import ttk
import subprocess
import csv
import os
from tkinter import messagebox
import mysql.connector

#Connect to DB
mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '123456',
    database = 'my_db',
    )

my_cursor = mydb.cursor()

#Parameters for window
root = Tk()
root.title("Пинг МКУ")
root.geometry("300x200")
root.resizable(width=False, height=False)
root['bg'] = '#ccc'

def write_to_csv(result):
    with open('results.csv', 'w') as employee_file:
        employee_writer = csv.writer(employee_file, dialect='excel')
        employee_writer.writerow([result])

#Chek our adresses
def CheckIP():
    results = []
    with open('ipping.txt', 'r') as f:
        for ip in f.read().splitlines():
            rv = subprocess.Popen(["ping", ip]).wait()
            results.append(ip+(" inactive" if rv else " active"))
    textVar.set('\n'.join(results))


Button(text='Пингануть',
       font='consolas 13',
       bg='#48494f',
       fg='#eff5c9',
       activeforeground='#eff5c9',
       activebackground='#6e6f73',
       width=22,
       height=2,
       command=CheckIP).pack()

textVar = StringVar()
Label(textvariable=textVar).pack(fill=X)


root.mainloop()```



热门问题