恐怖的OpenAI 代码+python功能

首先声明,我只是一个用C开发嵌入式的工程师,对Windows编程和Python UI功能一窍不通。但是通过OpenAi代码功能,我发现我居然能实现我大部分的PC软件自由。下面正文开始。

1.MD5 HMAC校验

怡笑大方,但对我来说,让我从头开始,学python UI,估计没那个时间。但claude2.0 的第一份代码,就能运行.平心而言,复杂点的还是用chatgpt4,但这个,用100k 聊得更欢。中间有部分我训练的过程。

import hmac

import hashlib

import tkinter as tk

def calculate_hmac():

key = key_entry.get().encode('utf-8')

message = message_entry.get().encode('utf-8')

hash_result = hmac.new(key, message, hashlib.md5).hexdigest()

result_text.delete(1.0, tk.END)

result_text.insert(tk.END, hash_result)

root = tk.Tk()

root.title("HMAC计算器")

key_label = tk.Label(root, text="Key:")

key_label.grid(row=0, column=0)

key_entry = tk.Entry(root)

key_entry.grid(row=0, column=1)

message_label = tk.Label(root, text="Message:")

message_label.grid(row=1, column=0)

message_entry = tk.Entry(root)

message_entry.grid(row=1, column=1)

calculate_button = tk.Button(root, text="计算", command=calculate_hmac)

calculate_button.grid(row=2, column=0)

result_label = tk.Label(root, text="Result:")

result_label.grid(row=3, column=0)

result_text = tk.Text(root)

result_text.grid(row=3, column=1)

root.mainloop()

From

一般这个脚本能得到正确的结果,但是当key或者message输入框中输入的字符包含一些特殊字符,如°C,它计算得到的结果就有误。要怎样修改?

S

您提到的问题是由于直接使用entry.get()获取输入时,不考虑文本编码导致的。

要解决这个问题,可以这么修改:

  1. 在获取key和message时,直接调用encode()方法进行utf-8编码:

python

Copy code

key = key_entry.get().encode('utf-8')
message
= message_entry.get().encode('utf-8')

  1. 另外需要在Label设置textvariable,也处理可能的特殊字符:

python

Copy code

key_label = tk.Label(root, textvariable=tk.StringVar(value='Key:'))
message_label = tk.Label(root, textvariable=tk.StringVar(value='Message:'))

  1. 设置Entry中的textvariable同样需要处理:

python

Copy code

key_var = tk.StringVar()
key_entry
= tk.Entry(root, textvariable=key_var)

message_var = tk.StringVar()
message_entry
= tk.Entry(root, textvariable=message_var)

这样,在获取key和message时,就可以直接从key_var和message_var中取值,就可以避免特殊字符导致的问题了。

总之,关键是在界面显示和取值时都需要处理文本编码,确保它们之间转化正确,就可以避免类似的问题。

Copy

别外message的文本输入框太小了,我需要大一点且有三行。

S

可以通过调整message的Entry组件的高度和宽度,并设置为多行文本来实现message文本框更大并且有三行的效果。

具体修改如下:

  1. 设置message Entry的高度,例如高度为3:

python

Copy code

message_entry = tk.Entry(root, width=30, height=3)

  1. 设置wrap属性为tkinter中的NONE,即换行显示:

python

Copy code

message_entry = tk.Entry(root, width=30, height=3, wrap='none')

  1. 用text替代Entry,来实现多行文本框:

python

Copy code

message_text = tk.Text(root, height=3, width=30)
message_text.grid(row
=1, column=1)

  1. 获取message时使用message_text.get('1.0', 'end-1c')

完整示例如下:

python

Copy code

message_text = tk.Text(root, height=3, width=30)
message_text.grid(row
=1, column=1)

# 其他代码

message = message_text.get('1.0', 'end-1c').encode('utf-8')

这样就可以实现一个高度为3行、宽度为30字符的多行message文本框了。可以根据需要调整高度和宽度。

Copy

我用的是python3.6,但显示_tkinter.TclError: unknown option "-height"

S

您遇到的这个问题是因为Python 3.6中的tkinter模块,其Entry组件还不支持"-height"这个选项。

解决方法是:

  1. 升级到Python 3.7或更高版本,其tkinter模块已经支持"-height"选项了。
  2. 如果无法升级Python版本,可以改用Text组件来实现多行文本框:

python

Copy code

import tkinter as tk

root = tk.Tk()

message_text = tk.Text(root, height=3, width=30)
message_text.grid(row
=1, column=1)

message = message_text.get('1.0', 'end-1c').encode('utf-8')

root.mainloop()

  1. 另外也可以使用pady参数来设置Entry的内部padding,间接达到多行的效果:

python

Copy code

message_entry = tk.Entry(root, width=30, pady=10)

  1. 如果必须用Entry,可以考虑使用Validation绑定来限制单行文本框的长度,模拟多行的效果。

所以解决思路主要有:

  • 升级Python版本
  • 改用Text组件
  • 调整padding
  • 使用Validation绑定限制长度

根据您的具体情况选择合适的方案即可。

2. ORC 利用https://api.ocr.space 公开的api来实现功能。

一开始只是实现功能,第一次即成功,这就是ai的准确性和可够性。后面不断加入新功能,例如加入设置代理服务器,再加入保存配置到文件等等。我想到的它都能完成。

文件读取与存储

窗口与上层窗口 UI

 

import requests

import tkinter as tk

from tkinter import filedialog, messagebox, Toplevel

import json

# {

# 'http': 'http://192.168.15.18:7890',

# 'https': 'http://192.168.15.18:7890',

# }

PROXY_FILE = 'proxy.json' # 存储代理设置的文件

# 将代理设置保存到文件中

def save_proxies(proxies):

with open(PROXY_FILE, 'w') as f:

json.dump(proxies, f)

# 从文件中载入代理设置

def load_proxies():

try:

with open(PROXY_FILE, 'r') as f:

proxies = json.load(f)

except FileNotFoundError:

proxies = None

return proxies

def open_proxy_window():

global proxies

proxy_window = Toplevel(window)

proxy_window.geometry('300x200')

proxy_window.title('Proxy Settings')

http_label = tk.Label(proxy_window, text='HTTP Proxy:')

http_label.pack(pady=10)

http_entry = tk.Entry(proxy_window, textvariable=http_proxy_var,width=50)

http_entry.pack(pady=5)

https_label = tk.Label(proxy_window, text='HTTPS Proxy:')

https_label.pack(pady=10)

https_entry = tk.Entry(proxy_window, textvariable=https_proxy_var, width=50)

https_entry.pack(pady=5)

def save_proxy():

global proxies

http_proxy = http_entry.get().strip("'\"")

https_proxy = https_entry.get().strip("'\"")

if http_proxy and https_proxy:

proxies = {

'http': http_proxy,

'https': https_proxy

}

elif http_proxy:

proxies = {

'http': http_proxy

}

elif https_proxy:

proxies = {

'https': https_proxy

}

else:

proxies = None

http_proxy_var.set(http_proxy)

https_proxy_var.set(https_proxy)

save_proxies(proxies) # 保存代理设置到文件中

proxy_window.destroy()

save_button = tk.Button(proxy_window, text='Save', command=save_proxy)

save_button.pack(side=tk.LEFT, padx=10)

cancel_button = tk.Button(proxy_window, text='Cancel', command=proxy_window.destroy)

cancel_button.pack(side=tk.RIGHT, padx=10)

def upload_file():

file_path = filedialog.askopenfilename()

file_entry.delete(0, tk.END)

file_entry.insert(tk.END, file_path)

def clear_text():

text_box.delete(1.0, tk.END)

def recognize_text():

api_key = 'xx17728xxxxx'

language = language_var.get()

file_path = file_entry.get()

if file_path.endswith('.pdf'):

payload = {'apikey': api_key, 'language': language}

with open(file_path, 'rb') as file:

response = requests.post('https://api.ocr.space/parse/pdf', files={'pdf': file}, data=payload, proxies=proxies)

else:

payload = {'apikey': api_key, 'language': language, 'isOverlayRequired': False}

with open(file_path, 'rb') as file:

response = requests.post('https://api.ocr.space/parse/image', files={'image': file}, data=payload, proxies=proxies)

result = response.json()

if result['IsErroredOnProcessing']:

text_box.insert(tk.END, 'Error occurred during OCR processing.')

else:

parsed_text = result['ParsedResults'][0]['ParsedText']

text_box.insert(tk.END, parsed_text)

# 创建主窗口

window = tk.Tk()

file_entry = tk.Entry(window, width=100)

file_entry.pack(pady=10)

window.title('OCR Text Recognition')

# proxies = None

http_proxy_var = tk.StringVar()

https_proxy_var = tk.StringVar()

proxies = load_proxies()

if proxies:

http_proxy_var.set(proxies.get('http', ''))

https_proxy_var.set(proxies.get('https', ''))

# 创建选择按钮和语言选择下拉菜单

select_button = tk.Button(window, text='Select File', command=upload_file)

select_button.pack(pady=10)

language_var = tk.StringVar(window)

language_var.set('eng') # 默认为英文

language_menu = tk.OptionMenu(window, language_var, 'eng', 'chs', 'cht', 'fre', 'ger', 'jpn', 'kor', 'spa')

# 可根据需求添加更多语言选项

language_menu.pack(pady=10)

# 创建识别按钮

recognize_button = tk.Button(window, text='Recognize', command=recognize_text)

recognize_button.pack(pady=10)

# 创建识别按钮

recognize_button = tk.Button(window, text='Set Proxy', command=open_proxy_window)

recognize_button.pack(pady=10)

# 创建文本框

text_box = tk.Text(window, height=20, width=100)

text_box.pack(pady=10)

# 创建清除按钮

clear_button = tk.Button(window, text='Clear', command=clear_text)

clear_button.pack(pady=10)

# 运行主循环

window.mainloop()

3. mqtt client with TSL

这是一个完整的实现过程,或者这个训练的过程对初学者更加有意义。它是用ChatGPT 4实现的。

我想用python来写一个支持mqtt 5.0协议的客户端,它的功能和mqttx 客户端类似,支持tsl的mqtt连接,可手动选择上传根证书,certificate.和private key.你能提供一个demo吗?
当然可以!以下是一个简单的示例代码,演示如何使用Python编写一个支持MQTT 5.0协议的客户端,并支持TLS连接和上传根证书、证书和私钥的功能:

python

import ssl
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("your_topic")

def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))

client = mqtt.Client(transport="tcp")
client.tls_set(ca_certs="path/to/root_certificate.pem", certfile="path/to/certificate.pem", keyfile="path/to/private_key.pem", tls_version=ssl.PROTOCOL_TLS)

client.on_connect = on_connect
client.on_message = on_message

client.connect("mqtt_server_address", 8883, 60)

client.loop_forever()
请你提供一个具有UI的版本,上面有broker,port的输入框,还有一个TSL选择框,如选中则有三个按键用于选择上传三个认证文件。有一个Connect按钮,点击后,上面所有的设置将发往broker验证并连接。如果连接出错,弹出出错提示。另外还有二个输入框用于输入订阅和发布的topic.还有一个多行文本框,如果连接成功,则在文本框中显示订阅接收到的内容。文本框下面有一个清除按键,用于清除已接收到的文本
以下是一个使用Python和Tkinter库编写的具有UI的示例代码,满足您的要求:

python

import ssl
import paho.mqtt.client as mqtt
import tkinter as tk
from tkinter import messagebox

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        messagebox.showinfo("Success", "Connected to MQTT broker!")
    else:
        messagebox.showerror("Error", "Failed to connect to MQTT broker!")

def on_message(client, userdata, msg):
    message_text.insert(tk.END, msg.topic + " " + str(msg.payload) + "\n")

def connect_to_broker():
    broker = broker_entry.get()
    port = int(port_entry.get())
    tls_enabled = tls_var.get()
    root_cert = root_cert_entry.get()
    cert = cert_entry.get()
    private_key = private_key_entry.get()

    client = mqtt.Client(transport="tcp")
    if tls_enabled:
        client.tls_set(ca_certs=root_cert, certfile=cert, keyfile=private_key, tls_version=ssl.PROTOCOL_TLS)

    client.on_connect = on_connect
    client.on_message = on_message

    try:
        client.connect(broker, port, 60)
        client.loop_start()
    except:
        messagebox.showerror("Error", "Failed to connect to MQTT broker!")

def clear_text():
    message_text.delete(1.0, tk.END)

root = tk.Tk()
root.title("MQTT Client")
root.geometry("400x300")

broker_label = tk.Label(root, text="Broker:")
broker_label.pack()
broker_entry = tk.Entry(root)
broker_entry.pack()

port_label = tk.Label(root, text="Port:")
port_label.pack()
port_entry = tk.Entry(root)
port_entry.pack()

tls_var = tk.BooleanVar()
tls_checkbox = tk.Checkbutton(root, text="Enable TLS", variable=tls_var)
tls_checkbox.pack()

root_cert_label = tk.Label(root, text="Root Certificate:")
root_cert_label.pack()
root_cert_entry = tk.Entry(root)
root_cert_entry.pack()

cert_label = tk.Label(root, text="Certificate:")
cert_label.pack()
cert_entry = tk.Entry(root)
cert_entry.pack()

private_key_label = tk.Label(root, text="Private Key:")
private_key_label.pack()
private_key_entry = tk.Entry(root)
private_key_entry.pack()

connect_button = tk.Button(root, text="Connect", command=connect_to_broker)
connect_button.pack()

subscribe_label = tk.Label(root, text="Subscribe Topic:")
subscribe_label.pack()
subscribe_entry = tk.Entry(root)
subscribe_entry.pack()

publish_label = tk.Label(root, text="Publish Topic:")
publish_label.pack()
publish_entry = tk.Entry(root)
publish_entry.pack()

message_text = tk.Text(root)
message_text.pack()

clear_button = tk.Button(root, text="Clear", command=clear_text)
clear_button.pack()

root.mainloop()
请确保在运行此代码之前安装了Tkinter库。此示例提供了一个基本的UI界面,您可以在其中输入MQTT服务器的地址、端口以及TLS相关的认证文件路径。单击"Connect"按钮将尝试连接到MQTT服务器,并在成功或失败时显示相应的提示。您还可以在"Subscribe Topic"和"Publish Topic"输入框中输入订阅和发布的主题。收到的消息将显示在文本框中,您可以使用"Clear"按钮清除文本框中的内容。

请注意,此示例仅提供了基本的UI框架,您可能需要根据您的需求进行进一步的定制和扩展。

三个认证证书的输入不只是label,而是要点按钮后显示选择文件对话框,选择完成后在label里显示选择的文件的路径。而且选择的文件最终要随ssl reuqest 传到broker供TSL认证用、
import ssl
import paho.mqtt.client as mqtt
import tkinter as tk
from tkinter import messagebox, filedialog

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        messagebox.showinfo("Success", "Connected to MQTT broker!")
    else:
        messagebox.showerror("Error", "Failed to connect to MQTT broker!")

def on_message(client, userdata, msg):
    message_text.insert(tk.END, msg.topic + " " + str(msg.payload) + "\n")

def connect_to_broker():
    broker = broker_entry.get()
    port = int(port_entry.get())
    tls_enabled = tls_var.get()
    root_cert = root_cert_path.get()
    cert = cert_path.get()
    private_key = private_key_path.get()

    client = mqtt.Client(transport="tcp")
    if tls_enabled:
        client.tls_set(ca_certs=root_cert, certfile=cert, keyfile=private_key, tls_version=ssl.PROTOCOL_TLS)

    client.on_connect = on_connect
    client.on_message = on_message

    try:
        client.connect(broker, port, 60)
        client.loop_start()
    except:
        messagebox.showerror("Error", "Failed to connect to MQTT broker!")

def select_root_cert():
    file_path = filedialog.askopenfilename()
    root_cert_path.set(file_path)

def select_cert():
    file_path = filedialog.askopenfilename()
    cert_path.set(file_path)

def select_private_key():
    file_path = filedialog.askopenfilename()
    private_key_path.set(file_path)

def clear_text():
    message_text.delete(1.0, tk.END)

root = tk.Tk()
root.title("MQTT Client")
root.geometry("400x400")

broker_label = tk.Label(root, text="Broker:")
broker_label.pack()
broker_entry = tk.Entry(root)
broker_entry.pack()

port_label = tk.Label(root, text="Port:")
port_label.pack()
port_entry = tk.Entry(root)
port_entry.pack()

tls_var = tk.BooleanVar()
tls_checkbox = tk.Checkbutton(root, text="Enable TLS", variable=tls_var)
tls_checkbox.pack()

root_cert_label = tk.Label(root, text="Root Certificate:")
root_cert_label.pack()
root_cert_path = tk.StringVar()
root_cert_entry = tk.Entry(root, textvariable=root_cert_path, state="readonly")
root_cert_entry.pack()
root_cert_button = tk.Button(root, text="Select", command=select_root_cert)
root_cert_button.pack()

cert_label = tk.Label(root, text="Certificate:")
cert_label.pack()
cert_path = tk.StringVar()
cert_entry = tk.Entry(root, textvariable=cert_path, state="readonly")
cert_entry.pack()
cert_button = tk.Button(root, text="Select", command=select_cert)
cert_button.pack()

private_key_label = tk.Label(root, text="Private Key:")
private_key_label.pack()
private_key_path = tk.StringVar()
private_key_entry = tk.Entry(root, textvariable=private_key_path, state="readonly")
private_key_entry.pack()
private_key_button = tk.Button(root, text="Select", command=select_private_key)
private_key_button.pack()

connect_button = tk.Button(root, text="Connect", command=connect_to_broker)
connect_button.pack()

subscribe_label = tk.Label(root, text="Subscribe Topic:")
subscribe_label.pack()
subscribe_entry = tk.Entry(root)
subscribe_entry.pack()

publish_label = tk.Label(root, text="Publish Topic:")
publish_label.pack()
publish_entry = tk.Entry(root)
publish_entry.pack()

message_text = tk.Text(root)
message_text.pack()

clear_button = tk.Button(root, text="Clear", command=clear_text)
clear_button.pack()

root.mainloop()


在上述代码中,我添加了三个按钮(Select),用于选择根证书、证书和私钥的文件。当用户点击这些按钮时,会弹出文件选择对话框,选择完成后,所选文件的路径将显示在相应的标签(Entry)中。在连接到MQTT代理时,所选文件的路径将传递给TLS设置。

请注意,您可能需要根据您的需求进一步调整和扩展此代码。

你可能感兴趣的:(python,microsoft,开发语言)