gpt4 book ai didi

Python3 和 Tkinter - 无法分配 27 个字节

转载 作者:行者123 更新时间:2023-12-03 17:24:42 30 4
gpt4 key购买 nike

在我的一段代码中,我的脚本生成一个字符串以将其复制到一个 scolled 文本小部件中。如果字符串的大小不是很重,这个过程没有任何问题,但是当字符串很重时,脚本不能将它粘贴到滚动的文本小部件中。当它发生时,脚本崩溃,终端中出现错误信息:unable to alloc 27 bytes (这不是异常事件)。
在崩溃之前,我通过 sys.getsizeof 获得了字符串的字节大小函数,它是 230031360 字节(230 MB)。
在这些情况下,用户可以解决选择在文本文件中写入输出消息的问题,但是如果用户尝试在 scolled 文本小部件中写入一个粗字符串怎么办?在这种特定情况下,我很想显示一个消息框来建议用户将输出写入文本文件,但是我如何理解脚本是否可以在滚动文本小部件中写入字符串? Python中字符串的字节限制是多少?
更新:
我写了一个例子来告诉你问题发生在哪里。主窗口将在大约两分钟内崩溃并在终端中显示错误消息,unable to alloc 28 bytes :

from tkinter import *
from tkinter import ttk, scrolledtext
import ipaddress

def GiveMeHosts():
ls = []
for host in ipaddress.ip_network("10.0.0.0/8").hosts():
ls.append(str(host))
return ls

parent = Tk()
parent.geometry("400x350")
parent.title("The window will crash..")

MyWidget=scrolledtext.ScrolledText(parent, wrap=WORD, width=36, height=14, font=("Segoe UI", 9), state="normal")
MyWidget.pack()

parent.update()

# the string "hosts" is too long, and "MyWidget" can't manage it!
hosts = "\n".join(GiveMeHosts())
MyWidget.insert("1.0", hosts) # it makes the script to crash

parent.mainloop()

最佳答案

我运行了您的代码,虽然花费了相当长的时间,但它最终确实将所有 IP 地址放入了滚动的文本框中。没有错误,也没有崩溃。顺便说一句:unable to alloc 28 bytes ,这正是最后两个ip地址的大小?!? (10.255.255.253 10.255.255.254)。
我又进了一步。其实就两步。试图运行相同的代码,但返回值相乘 ls *= 5 .结果仍然有效,没有崩溃。同时ls大小为 1790312344 bytes (1.67 GB) .
ls *=10然而,ls现在的大小为 2545286976 bytes (2.37 GB) ,它最终确实因以下回溯而崩溃:

Traceback (most recent call last):
File "F:\pybin\StackOverflow\so.py", line 28, in <module>
MyWidget.insert("1.0", hosts) # it makes the script to crash
File "C:\Program Files\Python36\lib\tkinter\__init__.py", line 3266, in insert
self.tk.call((self._w, 'insert', index, chars) + args)
OverflowError: string is too long
总而言之,似乎确实存在限制,但该限制很可能取决于系统。至少,这是我从中得出的结论。

关于Python3 和 Tkinter - 无法分配 27 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62431231/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com