Run py while true for about ten minutes, same problem, so not tkinter
python3.11
Case 1:
from 查询全部待打印标签 import get_all_labels
def click_button(print_num):
global text
# 问题在这里,调用了外部get_all_labels函数,在tkinter窗口打开一段时间后,再点击这个按钮,他不会运行这个函数了,直接快递的就return
trade_no_num = get_all_labels(print_num=print_num)
text.insert(tk.END, f'本次打印了{trade_no_num}笔订单标签 \t{time.now().strftime("%Y-%m-%d %H:%M:%S")}\n')
def thread_it(func, *args):
t = threading.Thread(get=func, args=args)
t.Daemon = True
t.start()
Print_all_Button = tk.Button(root, text='全部标签打印', bg='#7CCD7C', width=20, height=5,
command=lambda: thread_it(click_button, 2))
Print_all_Button.pack()
text = tk.Text(root)
text.pack()
root.mainloop()
The result of the
run:
Case 2:
import hashlib
import urllib.parse
import time
from datetime import datetime, timedelta
import jsonpath
import openpyxl
import requests
import win32com.client
def print_label(trade_no, print_num):
url_path = 'erp/opentrade/list/trades'
query_time = get_time(back_6_day.year, back_6_day.month, back_6_day.day, tomorow.year, tomorow.month,
tomorow.day)
# print(query_time)
data = {
'_app': appkey,
'_t': _t,
# 'bill_code': 'XD220808000014',
"pay_time": query_time[0],
'end_time': query_time[1],
'limit': '200',
'page': '1',
'trade_status': '1,2,3,4',
'is_split': '0'
}
_sign = hash_md5(joint(data, secretkey))
data['_sign'] = _sign
try:
res = requests.post(url + url_path, data=data)
# print(res.json())
if res.status_code == 200:
# print('post请求结果:', res.json())
# 提取数据
data = jsonpath.jsonpath(res.json(), '$..data')
# print(data)
data_list = []
for i in data[0]:
single_list = dict.fromkeys(
['平台', '店铺名', '系统单号', '平台订单状态', '系统订单类型', '买家ID', '省', '市', '区',
'订单明细',
'快递名称', '快递单号', '是否组合商品', '是否拆分订单', '是否售后订单', '异常类型名称', '包裹重量',
'创建时间'])
single_list['平台'] = jsonpath.jsonpath(i, '$..source_platform')
single_list['店铺名'] = jsonpath.jsonpath(i, '$..shop_nick')
single_list['系统单号'] = jsonpath.jsonpath(i, '$..trade_no')
single_list['平台订单状态'] = jsonpath.jsonpath(i, '$..oln_status')
single_list['系统订单类型'] = jsonpath.jsonpath(i, '$..trade_type')
single_list['买家ID'] = jsonpath.jsonpath(i, '$..buyer')
# ================================= 通过系统单号获取需要打印标签的组合商品名称 =================================#
query_Trade_No = trade_no
res = {'msg': '', 'id': ''}
# 定义组合名称列表
package_name = []
a = 0
for i in data_list:
if query_Trade_No in i.get('系统单号')[0]:
a += 1 # 判断系统单号是否存在
orders = i.get('订单明细')[0]
# print(orders)
for order in orders:
item_name = order.get('item_name') # 商品名称
sku_code = order.get('sku_code') # 规格编码
size = order.get('size') # 商品数量
price = order.get('price') # 单价(商品标价)
is_package = order.get('is_package') # 是否组合商品
receivable = order.get('receivable') # 应收(原价)
order_total_discount = order.get('order_total_discount') # 商品总优惠=原价-销售金额
payment = order.get('payment') # 应收款
tp_tid = order.get('tp_tid') # 线上单号
oln_item_id = order.get('oln_item_id') # 线上商品id
if not sku_code:
sku_code = '0'
if not oln_sku_id:
oln_sku_id = '0'
if 'A0' in sku_code or 'A0' in oln_sku_id:
if oln_sku_name:
res0 = oln_sku_name.strip('颜色分类:')
res1 = res0.strip('尺寸:')
res2 = res1.strip('5套起拍;')
res3 = res2.strip(';')
res4 = res3.strip('规格:')
package_name.append(res4)
elif item_name:
res0 = item_name.strip('颜色分类:')
res1 = res0.strip('尺寸:')
res2 = res1.strip('5套起拍;')
res3 = res2.strip(';')
res4 = res3.strip('规格:')
package_name.append(res4)
else:
res['msg'] = '该买家没有组合商品!'
break
if not package_name:
if a > 0:
res['msg'] = '该买家没有组合商品!'
else:
res['msg'] = '系统单号不正确!'
# print('通过系统单号查找的组合名称:', package_name)
else:
res['msg'] = '打印完成!'
for m in package_name:
# 读取excel文件,获取workbook对象
wb = openpyxl.load_workbook('E:/吊牌打印.xlsm', keep_vba=True)
# 通过名称获取工作薄
sheet = wb.active
# 插入一行数据
# sheet.append(["Hello", "World"])
# 具体修改哪一行那一列的数据
# 注意:cell的参数row、column必须是大于等于1的。
# sheet.cell(1, 5).value = '菁娇微景观'
sheet['B3'] = m
sheet['B2'] = len(package_name)
wb.save('E:/吊牌打印.xlsm')
wb.close()
xl = win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename=r"E:\吊牌打印.xlsm")
xl.Application.DisplayAlerts = False
for count in range(int(print_num)):
xl.Application.Run("打印标签")
# xl.Application.Save()
# xl.Application.DisplayAlerts = True
xl.Application.Quit()
time.sleep(0.3)
except:
pass
return res
if __name__ == '__main__':
while True:
trade_no_iput = input('请输入系统单号:')
print_label(trade_no=trade_no_iput, print_num=2)
error problem: Run the py file while True does not run all the time? At the beginning of the execution of the code can be, and then ten minutes later, the same result can appear(the result is the same as the last result), but in fact, no code execution, fast return, normal code execution to ten seconds, he so fast return results is not normal, and the background to see the print results,
0 Answer
Run py while true for about ten minutes, same problem, so not tkinter
the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > seems to be a Python program that defines a function print_label(trade_no, print_num), It takes two arguments: trade_no(a string) and print_num(an integer). The program imported several modules, including hashlib, urllib, time, datetime, jsonpath, openpyxl, requests, and win32com.client.
-
Inside the function, several variables are defined: url_path, query_time, data, and _sign. The function then uses the supplied data to send a POST request to the specified URL, using the requests module with the _app, _t, pay_time, end_time, limit, page, trade_status, and is_split parameters. The _sign parameter is evaluated using the hash_md5 function and is included in the data dictionary before the request is sent.
-
If the response status code is 200, the function uses the jsonpath module to extract data from the JSON response and assign it to the data_list. The function then walks through each element in the data_list and checks if the trade_no argument is a substring of the system order number(i.et(' system order number ')[0]). If so, append the res4 substring to the package_name list. If there is no element in the package_name list, the function sets the res['msg'] variable to 'This buyer has no combo item! '. If there are elements in the package_name list, the function sets the res['msg'] variable to 'print done! '.
-
Finally, the function loads the Excel workbook using the openpyxl module and walks through each worksheet in the workbook. If the worksheet name matches the string in the package_name list, the function prints the label. If the worksheet name does not match any of the strings in the package_name list, the function sets the res['id'] variable to 'the combination name is incorrect! '.
What I said was that I was able to run all the time from the beginning, and that was the presumption, that the code was fine, except if I didn't close it down for ten minutes or so
The problem may be caused by the tkinter mechanism, if the main thread is occupied by long calculations/loops, it will not be able to handle other events. Includes events that perform a button click when the user presses a key.
To solve this problem, long-running code can be placed in the background thread so that the main thread can continue to respond to events. You've implemented a function in your code called thread_it that takes a function as an argument and executes it in the background using threading.Thread.
So you can use this function to perform the get_all_labels function like this:
def click_button(print_num):
global text
thread_it(get_all_labels, print_num)
text.insert(tk.END, f'本次打印了{trade_no_num}笔订单标签 \t{time.now().strftime("%Y-%m-%d %H:%M:%S")}\n')
This moves the get_all_labels function to the background thread to avoid taking too long on the main thread. In addition, thread-safe GUI operations must be used to ensure that code executed in the background thread updates the GUI correctly.
In tkinter, variable types such as tkinter.stringvar or tkinter.intvar can be used to store the values of GUI components and update their values in the background thread using the set() method.
For example, you can create a tkinter.StringVar object for the text box text and use the text.set() method in the click_button function to set the value of the text box.
def click_button(print_num):
global text
thread_it(get_all_labels, print_num)
text.set(f'本次打印了{trade_no_num}笔订单标签 \t{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n')
This ensures that the value of the text box is updated in the background thread and avoids any long-running code execution in the main thread.
Code no problem, but when put up, delete some sensitive information, may delete the code is not complete. That doesn't affect my question.
Part of the answer refers to GPT, GPT_Pro is better for solving the problem
After running python for a long time, some of the code in def will not execute, but will display the result. It's usually because there's something wrong in the code, or something in the def that can't be done.
To solve this problem, we need to figure out what this code does. What does it do? Let's see if there are any errors in this code. Or an operation that cannot be performed?
Let's first look at what this code does:
import get_all_labels from import get_all_labels(), call get_all_labels() from click_button(), pass the print_num parameter, and insert the value of trade_no_num in text; Create thread t in function thread_it() and pass the click_button() function and argument 2 into t for execution; Call the thread_it() function in Print_all_Button.
Let's see if there's anything wrong with this code:
There's nothing between line 2 and line 3; The "=" sign is missing from the assignment statement for the trade_no_num variable in line 6; The "," sign is missing from the definition of the thread_it() function on line 9.
There are also operations that cannot be performed:
When we call the thread_it() function in Print_all_Button, we pass click_button() and 2, but the click_button() function needs the print_num argument to execute properly.
The modified code is as follows:
from 查询全部待打印标签 import get_all 1abels
def click_button(print_num):
global text
trade_no_num = get_all_labels(print_num=print_num)
text.insert(tk.END,trade_no_num)
def thread it(func,*args):
t = threading.Thread(target=func,args=args)
t.daemon = True
t.start()
Print_al1_Button = tk.Button(root,text="",bg="",width=286,height-5,command=lambda: thread_it(click_button,2,print_num))
Print_all_Button.pack()
text = tk.TextCroot
If the answer is helpful, please accept it.
这家伙很懒,什么都没留下...