首页 > 解决方案 > Python3 和 Tkinter - 无法分配 27 个字节

问题描述

在我的一段代码中,我的脚本生成一个字符串以将其复制到一个 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()

标签: pythontkinter

解决方案


我运行了您的代码,虽然花费了相当长的时间,但它最终还是将所有 IP 地址放入了滚动的文本框中。没有错误,也没有崩溃。顺便说一句:unable to alloc 28 bytes这正是最后两个IP地址的大小?!?(10.255.255.253 10.255.255.254)。

我又进了一步。其实分两步。试图运行相同的代码,但乘以返回值ls *= 5。结果仍然有效,没有崩溃。同时ls有一个大小1790312344 bytes (1.67 GB)

然而ls *=10ls现在的大小为2545286976 bytes (2.37 GB),它最终确实崩溃了,并出现了以下 Traceback:

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

总而言之,似乎确实存在一个限制,但该限制很可能取决于系统。至少,这是我从中得出的结论。


推荐阅读